Isaac said:
ok i under stand everything but this in the 2nd answer. I mean it must
be with telling it to go to the next array for i but idk could you tell
me a play by play of whats happening
Isaac said:
ok i under stand everything but this in the 2nd answer. I mean it must
be with telling it to go to the next array for i but idk could you tell
me a play by play of whats happening
These blocks are hard to grasp in the beginning. Once you get the hang
of it,
they are real easy. OK let's go:
numbers=["one", "two", "three"]
numbers now represents a list of values. This list is in a specific
order.
Ruby starts counting at zero, so :
0 "one"
1 "two"
2 "three"
The 0,1,2 are called indexes (also: indices). numbers[1] will give you
"two".
The "one", "two", "three" bit is called: values.
You have seen what the method .each does in
numbers.each do |number|
It will stuff every value of "numbers", one by one, in the variable
"number".
Sometimes you want both the value and the index to do all kinds of smart
things; and there it is: each_with index.
But if we ask two things, we'd better have two variables to hold them.
Let's call the second one "index". (After a while you'll probably get
tired of typing "index" all the time and just choose the lazy "i").
numbers=["one", "two", "three"]
numbers.each_with_index do |number, index|
print index + 1 # smart thing
puts ": " + number
puts
end
There is a LOT of methods to be learned. Most of them are surprisingly
simple, some of them have very powerfull features. You can google them
(ruby each_with_index), you can use ri (start a cmd box, or a session or
whatever in Linux; if it's a black box with a blinking cursor you'll be
fine. Type "ri each_with_index". Or type "irb" and start toying). And
there is always
http://tryruby.hobix.com/ to get you going.