rubyruby-block

How to chain a method call to a `do ... end` block in Ruby?


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

Solution

  • 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..