如何重述if语句

jok*_*lan 3 ruby if-statement

我有这个嵌套的if语句,我无法弄清楚如何重构它...它非常简单,但我无法得到正确的想法,希望有人可以提供帮助.

首先,我有一个嵌套的if语句(坏):

unless record.valid?
  if condition_1
    action_1
  elsif condition_2
    action_2
  elsif condition_3
    action_3
  end
end
Run Code Online (Sandbox Code Playgroud)

然后我尝试了这个,但这看起来没有任何好转(如果没有任何内部的if语句也是坏的):

if record.valid?
  # do nothing
elsif condition_1
  action_1
elsif condition_2
  action_2
elsif condition_3
  action_3
end
Run Code Online (Sandbox Code Playgroud)

有没有人知道如何重构这些语句,以便它看起来更好?

更新:解决方案(基于@thomasfedb和@undur_gongor)

我最终做的只是:

return if record.valid?

if condition_1
  action_1
elsif condition_2
  action_2
elsif condition_3
  action_3
end
Run Code Online (Sandbox Code Playgroud)

tho*_*edb 6

如果您利用Ruby的各种if/ unless语法和case语句,您可能会觉得它更整洁.如果您要使用方法进行换行,您也可以利用它return.

def check_record(record)
  return unless record.valid?

  case record.some_property
  when 1
    do_something
  when 2
    do_whatever
  when 3
    do_a_dance
  end
end
Run Code Online (Sandbox Code Playgroud)


und*_*gor 5

Mapping = { :has_value_1? => :method_1, 
            :has_value_2? => :method_2, 
            :has_value_3? => :method_3 }

unless record.valid?
  Mapping.each_pair do | k, v | 
    next unless record.send(k)
    record.send(v)
    break
  end
end
Run Code Online (Sandbox Code Playgroud)

请注意,在非常旧的Ruby版本(1.9之前)中,哈希没有排序.如果属性的顺序很重要,那么在这种情况下需要一组对.剩下的代码几乎是一样的.

更新后的问题(并根据thomasfedb的提议):

def check_record(record)
  return unless record.valid?

  return action_1 if condition_1
  return action_2 if condition_2
  return action_3 if condition_3

  nil
end
Run Code Online (Sandbox Code Playgroud)