How is it possible to chain methods in Ruby when the method calls are specified as an array?
Example:
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
[Note to Ruby purists: stylistic liberties were taken with this example. For notes on preferred usage regarding semicolons, parenthesis, comments and symbols, please feel free to consult Ruby style guides (e.g., https://github.com/styleguide/ruby)]
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With