Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails map_with_index?

Tags:

ruby

I have the following:

    :participants => item.item_participations.map { |item|
      {:item_image => item.user.profile_pic.url(:small)}
    }

I want this to happen no more than 3 times inside. I tried map_with_index but that did not work.

Any suggestions on how I can break after a max of 3 runs in the loop?

like image 954
AnApprentice Avatar asked Dec 22 '10 03:12

AnApprentice


People also ask

What does map do in Rails?

You use map to collect the result of running the block over the elements of the array. And you use each to run the block over the elements without collecting the values. You can read more about using the each method here.

What is the difference between each and map in rails?

So each is used for processing an array and map is used to do something with a processed array.

What does &: mean in Ruby?

In a method argument list, the & operator takes its operand, converts it to a Proc object if it isn't already (by calling to_proc on it) and passes it to the method as if a block had been used.

How do you create a map in Ruby?

Ruby Map SyntaxFirst, you have an array, but it could also be a hash, or a range. Then you call map with a block. The block is this thing between brackets { ... } . Inside the block you say HOW you want to transform every element in the array.


1 Answers

As of Ruby 1.9, you can use map.with_index:

:participants => item.item_participations.map.with_index { |item, idx|
  {:item_image => item.user.profile_pic.url(:small)}
  break if i == 2  
}

Although I kind of prefer the method proposed by Justice.

like image 196
Brian Deterling Avatar answered Oct 15 '22 04:10

Brian Deterling