Ruby:如何链接方法的数组(或拆分字符串)中指定的方法?

时间:2013-04-15 20:43:10

标签: ruby methods chaining

当方法调用指定为数组时,如何在Ruby中链接方法?

示例:

class String
  def bipp();  self.to_s + "-bippity"; end
  def bopp();  self.to_s + "-boppity"; end
  def drop();  self.to_s + "-dropity"; end
end

## this produces the desired output
##
puts 'hello'.bipp.bopp.drop #=> hello-bippity-boppity-dropity

## how do we produce the same desired output here?
##
methods   =   "bipp|bopp|drop".split("|")
puts 'world'.send( __what_goes_here??__ ) #=> world-bippity-boppity-droppity

[对Ruby纯粹主义者的注意:这个例子采用了风格自由。有关分号,括号,注释和符号的首选用法的注释,请随时查阅Ruby样式指南(例如,https://github.com/styleguide/ruby)]

2 个答案:

答案 0 :(得分:9)

试试这个:

methods   =   "bipp|bopp|drop".split("|")
result = 'world'
methods.each {|meth| result = result.send(meth) }
puts result

或使用inject

methods = "bipp|bopp|drop".split("|")
result = methods.inject('world') do |result, method|
  result.send method
end

或者更简单地说:

methods = "bipp|bopp|drop".split("|")
result = methods.inject('world', &:send)

顺便说一下 - Ruby在每一行的末尾不需要分号;

答案 1 :(得分:1)

methods   =   "bipp|bopp|drop".split("|")
result = 'world'
methods.each {|meth| result = result.method(meth).call }
puts result #=> world-bippity-boppity-dropity

methods = "bipp|bopp|drop".split("|")
methods.each_with_object('world') {|meth,result| result.replace(result.method(meth).call)} #=> world-bippity-boppity-dropity