MattSom
MattSom

Reputation: 2377

Ruby assign do-block to array

I'm a newbie Rails learner. I want to try out some ruby language features, e.g. shorten the following method:

def update(params)
  attrs = []
  params[:attributes].each do |attr_hash| 
    attr = Attribute.new attr_hash
    attrs.push attr
  end
  ...
end

like:

def update(params)
   attrs = fill_attrs_from_params params
   ...
end

def fill_attrs_from_params(params)
  attrs = params[:attributes].each do |attr_hash| 
    Attribute.new(attr_hash)
  end
end

The second doesn't work as the first one however. What do I miss here?

Edit: I couldn't really decide how the second one worked, the application went buggy, and I'm a beginner with rails debugging as well.

Upvotes: 1

Views: 409

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

That's what .map is for

  attrs = params[:attributes].map do |attr_hash| 
    Attribute.new(attr_hash)
  end

.each is very versatile. With a bit of helper code, you can make it do anything. And that is its weakness. When you think to use .each, there's almost always a method on Enumerable that does the job better with less code (of course, except the obvious use case: performing an action on each element of a collection. Here you use .each.)

Upvotes: 4

Related Questions