Ruby has support for functional programming features like code blocks and higher-level functions (see Array#map, inject, & select).
How can I write functional code in Ruby?
Would appreciate examples like implementing a callback.
Ruby has support for functional programming features like code blocks and higher-level functions (see Array#map, inject, & select).
How can I write functional code in Ruby?
Would appreciate examples like implementing a callback.
You could use yield
def method(foo,bar)
operation=foo+bar
yield operation
end
then you call it like this:
foo=1
bar=2
method(foo,bar) {|result| puts "the result of the operation using arguments #{foo} and #{bar} is #{result}"}
the code in the block (a block is basically "a chunk of code" paraphrasing ruby programmers) gets executed in the "yield operation" line, you pass the method a block of code to be executed inside the method defined. This makes Ruby pretty versatile language.
In this case yield receives an argument called "operation". I wrote it that way because you asked for a way to implement a callback.
but you could just wrote
def method()
puts "I'm inside the method"
yield
end
method(){puts "I'm inside a block"}
and it would output
I'm inside the method
I'm inside a block