Table of Contents [hide]
Passing a hash to a method ∞
def foo( hash ) p hash[:a] p "yay" end foo( { :a=>'testing!' } )
Passing a method name using yield ∞
A simple example:
def example_one return "This is example one" end def example_two return "This is example two" end def example_yield() puts yield end example_yield() { example_one() } example_yield() { example_two() }
A more complex example ∞
You can also pass a different number of parameters, and deal with them intelligently.
# First you set up a method which can handle a yield: def yield_method( string, *splat ) array = string.split( ' ' ) array.each_index { |i| next if i.odd? array[i] = yield( array[i], splat ) } return array end # Then you set up one or more methods which you'd like to pass to the above method: def example_method( string, *array ) if array.size > 0 then append = ' ' + array[0..-1].join( ' ' ) else append = '' end string = "{#{ string }}#{append}" return string end # You use all of this like so: p yield_method( "one two three four" ) { |i| example_method( i ) }.join( ' ' ) p yield_method( "one two three four" ) { |i| example_method( i, 'hello' ) }.join( ' ' )
Last updated 2016-12-27 at 21:26:40