簡體   English   中英

編寫基於Ruby中的一組條件返回方法的方法的更好方法

[英]Better way to write methods that return methods based on a set of conditions in Ruby

我遇到了一個問題,對於這種紅寶石方法,其循環復雜度太高:

def find_value(a, b, lookup_value)
  return find_x1(a, b) if lookup_value == 'x1'
  return find_x2(a, b) if lookup_value == 'x2'
  return find_x3(a, b) if lookup_value == 'x3'
  return find_x4(a, b) if lookup_value == 'x4'
  return find_x5(a, b) if lookup_value == 'x5'
  return find_x6(lookup_value) if lookup_value.include? 'test'
end

有什么辦法可以寫而不必使用eval嗎?

嘗試這個:

def find_value(a, b, lookup_value)
  return find_x6(lookup_value) if lookup_value.include? 'test'
  send(:"find_#{lookup_value}", a, b)
end

send()允許您使用字符串或符號通過名稱來調用方法。 第一個參數是方法的名稱; 以下參數僅傳遞給被調用的方法。

如果需要一些靈活性,查找方法或類名也沒有錯:

LOOKUP_BY_A_B = {
  'x1' => :find_x1,
  'x2' => :find_x2,
  'x3' => :find_x3,
  'x4' => :find_x4,
  'x5' => :find_x5,
}.freeze

def find_value(a, b, lookup_value)
  method = LOOKUP_BY_A_B[lookup_value]
  return self.send(method, a, b) if method
  find_x6(lookup_value) if lookup_value.include? 'test'
end

您還可以查找Procs,類似

MY_PROCS = {
  1 => proc { |a:, b:| "#{a}.#{b}" },
  2 => proc { |a:, b:| "#{a}..#{b}" },
  3 => proc { |a:, b:| "#{a}...#{b}" }
}.freeze

def thing(a, b, x)
  MY_PROCS[x].call(a: a, b: b)
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM