DEV Community

Maylene Poulsen
Maylene Poulsen

Posted on

Chaining a method on a do...end block in Ruby

I am brand new to coding and working with Ruby so I learn something new every day! I am also a student at the Austin Flatiron School. Sometimes I need to use a method on the returned array from a Ruby do...end block. Usually, I would set the do...end block equal to a variable and then call a method on this variable.

But I learned an easier way. I wanted to enumerate through an array of Ruby objects (ExampleClass.all) and return some data from each object. Then I wanted to use the .sum method to find the total number of pets.

ExampleClass.all => [<@name= "Sydney", @pets= 3>,
               <@name= "Sophie", @pets= 4>,<@name= "Phineas", @pets= 1>,
               <@name= "Mark", @pets= 6>]
array_of_number_of_pets = ExampleClass.all.map do |object|
                             object.pets
                           end  

array_of_number_of_pets  => [3, 4, 1, 6]

array_of_number_of_pets.sum => 14

Or you could just chain the sum method onto the "end" in the do...end block

ExampleClass.all.map do |object|
  object.pets
end.sum

  => 14

Top comments (0)