Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 359
MattSom Avatar asked Jun 08 '17 11:06

MattSom


People also ask

Can you chain methods in Ruby?

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.

What are procs in Ruby?

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.

What is block given in Ruby?

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.

What is call method in Rails?

call evaluates the proc or method receiver passing its arguments to it.


1 Answers

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

like image 120
Md. Farhan Memon Avatar answered Oct 05 '22 20:10

Md. Farhan Memon