shaz
1
Is it possible to add to the name of a hash while running through an
iteration? What I’m trying to achieve:
SomeArray.each do |i, name, content|
info[i+1] = { “name” => name, “content” => content }
end
So that I can call, for example info[1] [name] or info[5][content]…
shaz
2
On 08.04.2010 03:27, Shaz wrote:
Is it possible to add to the name of a hash while running through an
iteration? What I’m trying to achieve:
SomeArray.each do |i, name, content|
info[i+1] = { “name” => name, “content” => content }
end
So that I can call, for example info[1] [name] or info[5][content]…
Make info an Array and just use
info << { :name => name, :content => content }
Kind regards
robert
shaz
3
Is this what you want?
SomeArray.each_with_index do |(name,content),i|
…
end
shaz
4
Shaz wrote:
Each with index worked for me - didn’t realize each variable in the
array has an index that can be called.
Not exactly. The ‘each_with_index’ method just yields the array index to
the block being called.
Inside it will be implemented something like this:
module Enumerable
def each_with_index
i = 0
each do |elem|
yield elem, i
i += 1
end
end
end
But you could consider it like this:
class Array
def each_with_index
size.times do |i|
yield self[i], i
end
end
end
shaz
5
On 8 Apr, 08:44, Brian C. [email protected] wrote:
Is this what you want?
SomeArray.each_with_index do |(name,content),i|
…
end
–
Posted viahttp://www.ruby-forum.com/.
Each with index worked for me - didn’t realize each variable in the
array has an index that can be called. Thanks!
shaz
6
On Sun, Apr 11, 2010 at 5:32 PM, Li Chen [email protected] wrote:
end
end
- which one is the reciever for “each”?
- which one is the reciever for “size”?
When there’s no explicit receiver, the method call happens on the
object that is “self” at that point.
Jesus.
shaz
7
Jesús Gabriel y Galán wrote:
On Sun, Apr 11, 2010 at 5:32 PM, Li Chen [email protected] wrote:
� � end
� end
- which one is the reciever for “each”?
- which one is the reciever for “size”?
When there’s no explicit receiver, the method call happens on the
object that is “self” at that point.
Jesus.
Hi Gabriel,
Where can I find more info about method call on implicit receiver?
Li
shaz
8
On 4/11/10, Li Chen [email protected] wrote:
Where can I find more info about method call on implicit receiver?
Seems like we’ve had a number of newbies who’ve been perplexed about
this recently. Maybe this should be in the faq. Isn’t there a faq
somewhere?
shaz
9
Brian C. wrote:
Inside it will be implemented something like this:
module Enumerable
def each_with_index
i = 0
each do |elem|
yield elem, i
i += 1
end
end
end
But you could consider it like this:
class Array
def each_with_index
size.times do |i|
yield self[i], i
end
end
end
Hi Brian,
Just some follow-up questions for these codes:
I recall the the method call in Ruby follow this format:
“receiver.method”
So
- which one is the reciever for “each”?
- which one is the reciever for “size”?
Thanks,
Li