This is done by passing methods via blocks. There are several syntaxes for this.
The first syntax uses yield and looks something like this.
def method1
puts "This is from method 1"
yield
end
def method2
puts "This is from method 2"
end
method1(){method2}
The above will output
This is from method 1
This is from method 2
The second option uses the following syntax
def method1(&block)
puts "This is from method 1"
block.call
end
def method2
puts "This is from method 2"
end
method1(){method2}
The output results are the same. Typically the yield syntax is preferred as it is more terse, but also because it is on average about 5X as fast as the block.call notation.
The third option is to use the send syntax which looks like follows.
def method1(method_name_string)
puts "This is from method 1"
send(method_name_string, 1, 2)
end
def method2(a,b)
puts "This is from method 2" + a.to_s + ' ' + b.to_s
end
method1("method2")
You can also achieve something similar using lambda or Proc.new
def method1(lmb)
puts "This is from method 1"
block.call "A string"
end
foo = lambda do |x|
puts x
end
method1(foo)
In this case you would see
This is from method 1
A string