我已阅读 this question ,但我无法创建完整示例:
class Some
def method_a
puts "a"
end
def method_b
puts "b"
end
def method_c
puts "c"
end
end
some = Some.new
a = true
b = true
c = true
l = []
l << :method_a if a
l << :method_b if b
l << :method_c if c
l.inject(some) { |obj, method|
obj.send(method)
}
[demas @arch.local.net ][~/dev/study/ruby/oop]% ruby inject_ex.rb
ainject_ex.rb:26:in
block in <main>': undefined method
method_b' for nil:NilClass(NoMethodError)
from inject_ex.rb:26:in `each'
from inject_ex.rb:26:in `inject'
from inject_ex.rb:26:in `'
最佳答案
Inject 将 block 的返回值传递给下一次迭代。现在,您的 obj
在第一次迭代后具有 obj.send(:method_a)
的返回值。像这样修复你的注入(inject):
l.inject(some) { |obj, method|
obj.send(method)
obj
}
关于ruby - ruby 中的条件链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1807487/