4

当方法调用被指定为数组时,如何在 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)]

4

2 回答 2

12

Try this:

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

or, using inject:

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

or, more briefly:

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

By the way - Ruby doesn't need semicolons ; at the end of each line!

于 2013-04-15T20:48:01.357 回答
2
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
于 2013-04-15T20:58:50.637 回答