编写基于Ruby中一组条件返回方法的方法的更好方法

时间:2017-07-20 16:26:21

标签: ruby cyclomatic-complexity

我遇到了这个ruby方法的Cyclomatic复杂性太高的问题:

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

2 个答案:

答案 0 :(得分:4)

试试这个:

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()允许您使用字符串或符号按名称调用方法。第一个参数是方法的名称;以下参数只传递给被调用的方法。

答案 1 :(得分:2)

如果您需要一些灵活性,查找方法或类名没有错:

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