Reputation: 135
Can I get all items been created in loop with ruby on rails?? Here my example:
@fb_data_hash = {:key1 => value1, :key2 => value2, :key3 => value3, ...}
@fb_data_hash.each do |key, val|
timeline = get_id_and_content(key, val)
#timeline will be created like this:
=>first: timeline = {:id => "1", :content => "abcd"}
=>second: timeline = {:id => "2", :content => "efgh"}
=>third: timeline = {:id => "3", :content => "ijkl"}
end
So, I want to get all timeline each time it been created, like this:
alltimelines = [{:id => "1", :content => "abcd"},{:id => "2", :content => "efgh"},{:id => "3", :content => "ijkl"}]
<=>
alltimelines = [timeline(first),timeline(second),timeline(third)]
But, I don't know how to do that, I tried create an array like this:
alltimelines = Array.new
alltimelines << timeline
but, it just get one timeline in first. Please help me :)
Upvotes: 0
Views: 88
Reputation: 42869
You could simply use Enumerable#collect
which will return a new array by running a block on each item of the enumerable, but also it won't destroy or modify the old variable
timeline = @fb_data_hash.collect { |key, val| get_id_and_content(key, val) }
# @fb_data_hash is still intact
# timeline has the data that you want
Upvotes: 1
Reputation: 579
If you really want this format with an array like:
all_timelines = [{:id => "1", :content => "abcd"},{:id => "2", :content => "efgh"},{:id => "3", :content => "ijkl"}]
This code should do the trick (assuming the fact that @fb_data_hash actually contains data) :
all_timelines = Array.new
@fb_data_hash.each do |key, val|
all_timelines.push({:id => key, :content => val})
end
Then you can call your array like that (as an exemple)
all_timelines.first # return {:id=>1, :content=>"abcd"}
Hope that is you are looking for.
Upvotes: 0
Reputation: 4555
You can use map
for this purpose
some_hash = { key: "value", other_key: "other_value" }
some_hash.map do |key, val|
get_id_and_content(key, val)
end
# => equivalent to [ get_id_and_content(:key, "value"), get_id_and_content(:other_key, "other_value") ]
Upvotes: 2