dreftymac
dreftymac

Reputation: 32440

Ruby: How to chain methods specified in an array (or split string) of methods?

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)]

Upvotes: 4

Views: 2536

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118299

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

or

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

Upvotes: 2

Chowlett
Chowlett

Reputation: 46685

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!

Upvotes: 12

Related Questions