--------------------------------------------------------------------
Same as +Array#each+, but passes the index of the element instead
of the element itself.
In message "Re: Strange about Array#each_index" on Tue, 26 Dec 2006 03:51:19 +0900, Li Chen <chen_li3@yahoo.com> writes:
I query Ruby about Array#each_index and here are what Ruby returns:
--------------------------------------------------- Array#each_index
array.each_index {|index| block } -> array
--------------------------------------------------------------------
Same as +Array#each+, but passes the index of the element instead
of the element itself.
Try it in a program file : irb use to print the "inspect" method of
every object used.
Thank you all.
It looks like there are some differences between running a script from
irb and the command line. I should try them both before I post questions
in the future.
Try it in a program file : irb use to print the "inspect" method of
every object used.
It looks like there are some differences between running a script from irb and the command line. I should try them both before I post questions in the future.
I am not sure whether you understood the point properly - please ignore if I'm just adding line noise. Yes, there are differences in the treatment of local variables. IRB also prints out the result of invoking #inspect on each expression that you pass on to evaluation. Other than that each_index behaves identically in IRB and in a script. In your first posting you say
According to the above Array#each_index will return only the index for
each element: 0,1,2.
and
But when I paste the codes and run on my XP I find Ruby returns both
indexes and values. Do I miss something?
each_index always *returns* the receiver (i.e. the Array or whatever you invoke that method on) and each_index *passes* every index to the block. The fact that you see both is just a consequence of the fact that both routes eventually print something to the screen. So the crucial bit to distinguish is *passing* values to a block and *returning* values from a method.
each_index always *returns* the receiver (i.e. the Array or whatever you
invoke that method on) and each_index *passes* every index to the block.
A few more examples to help clarify:
# Do nothing in the block and see what is returned
p %w|a b c|.each_index{ }
# => ["a", "b", "c"]
# How about the #times method?
p 3.times{ }
#=> 3
# Apparently it returns the last index passed to the block
# Let's write our own
def foo; yield; end
p foo{ 'a' }
#=> 'a'
# Our method returns whatever the block returns
# Now, let's return something else
def foo
yield 42
'bar'
end
p foo{ |x| p x }
#=> 42
#=> "bar"
That last example is like each_index; it doesn't matter what you do in
the block, the method ends up returning a different value from what
your block returns.