I want to create a filter, and be able to apply it to an array or hash. For example:
def isodd(i) i % 2 == 1 end
The I want to be able to use it like so:
x = [1,2,3,4] puts x.select(isodd) x.delete_if(isodd) puts x
This seems like it should be straight forward, but I can't figure out what I need to do it get it to work.
When using parameters prefixed with ampersands, passing a block to a method results in a proc in the method's context. Procs behave like blocks, but they can be stored in a variable. Lambdas are procs that behave like methods, meaning they enforce arity and return as methods instead of in their parent scope.
There are only two main differences. First, a lambda checks the number of arguments passed to it, while a proc does not. This means that a lambda will throw an error if you pass it the wrong number of arguments, whereas a proc will ignore unexpected arguments and assign nil to any that are missing.
Create a lambda and then convert to a block with the &
operator:
isodd = lambda { |i| i % 2 == 1 } [1,2,3,4].select(&isodd)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With