Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 903
dreftymac Avatar asked Dec 08 '22 16:12

dreftymac


1 Answers

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!

like image 93
Chowlett Avatar answered Dec 11 '22 11:12

Chowlett