1

I'm fairly new to ruby and its rubyisms, I have a code similar to this one :

def my_method objects
  temp = []

  objects.each do |o|
    temp <<  {
      :text => o.text,
      :title => o.title
    }
  end

  return temp
end

Could you help me to write this better ? Or show me some sources to learn this kind of rubyisms plz ? I'm already doing the ruby koans lessons.

lucapette
  • 20,564
  • 6
  • 65
  • 59
Flyingbeaver
  • 375
  • 4
  • 18

2 Answers2

8

You could use map:

def my_method objects
  objects.map { |e| {text: e.text, title: e.title} }
end

About the resources: I strongly recommend reading Eloquent Ruby.

Edit

I used the Ruby 1.9.x hash syntax.

lucapette
  • 20,564
  • 6
  • 65
  • 59
1

objects.collect{|o| {:text=> o.text, :title => o.title} }

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176