I'm doing the following:
array_variable = collection.map do |param|
some value with param
end
return array_variable.compact
Can I call map
and compact
in one statement somehow, so I can return the result instantly?
I'm thinking on something like this (it may be invalid, however):
array_variable = block_code param.compact
# block_code here is a method for example which fills the array
Method chaining is a convenient way to build up complex queries, which are then lazily executed when needed. Within the chain, a single object is updated and passed from one method to the next, until it's finally transformed into its output value.
A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.
A block is the same thing as a method, but it does not belong to an object. Blocks are called closures in other programming languages. There are some important points about Blocks in Ruby: Block can accept arguments and returns a value.
call evaluates the proc or method receiver passing its arguments to it.
yes, you can call a method here.
In your case,
array_variable = collection.map do |param|
# some value with param
end.compact
OR
array_variable = collection.map{ |param| some value with param }.compact
As pointed out by @Stefan, assignment is not required, you can directly use return
and if that's the last line of method you can omit return
too..
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