我需要执行以下代码
if var == 1
#some code #1
elsif var == 2
#some code #1 + some code #2
elsif var == 3
#some code #1 + some code #2 + some code #3
elsif var == 4
#some code #1 + some code #2 + some code #3 + some code #4
end
如何在不复制代码的情况下重写它?
我需要执行以下代码
if var == 1
#some code #1
elsif var == 2
#some code #1 + some code #2
elsif var == 3
#some code #1 + some code #2 + some code #3
elsif var == 4
#some code #1 + some code #2 + some code #3 + some code #4
end
如何在不复制代码的情况下重写它?
我假设您想要执行副作用,一个选项是将代码移动到块并随意执行。我假设这些调用都是同质的:
proc1 = proc { ... }
proc2 = proc { ... }
proc3 = proc { ... }
case var
when 1
proc1.call
when 2
proc1.call
proc2.call
when 3
proc1.call
proc2.call
proc3.call
end
这相当于:
[proc1, proc2, proc3, ....].take(var).each(&:call)
请改用 switch 语句:
case var
when 1
puts "It's 1"
when 2
puts "It's 2"
when 3
puts "It's 3"
when 4
puts "It's 4"
else
puts "None of the above"
end
如果你真的想使用 if 语句,你可以使用简写:
puts 'It's 1' if var == 1
puts 'It's 2' if var == 2
if var > 0
# code 1
end
if var > 1
# code 2
end
if var > 2
# code 3
end
不需要在一个大的 if 或 case 块中运行整个事情,除非您遇到特殊情况,例如您只想运行代码 3 和代码 5(在这种情况下,我会按照 tokland 的建议构建 proc 数组)
创建不同的方法并调用它们。
def method1
return "Do "
end
def method2
return "you "
end
def method3
return "believe "
end
def method4
return "in magic"
end
print "Type in a number between 1-4\nNumber: "
number = gets.chomp.to_i
case number
when 1
puts method1
when 2
puts method1 + method2
when 3
puts method1 + method2 + method3
when 4
puts method1 + method2 + method3 + method4
else
puts "Something something..."
end