First of all, it's "gets" and "each" - ruby is case sensitive ![:slight_smile: :slight_smile:](https://emoji.discourse-cdn.com/twitter/slight_smile.png?v=12)
Okay, so "gets" waits for the user to enter a line of text (that is,
to type in a bunch of characters and then hit enter). It then returns
that text as a string. Here's an example:
while true
print "say something: "
a = gets
puts "you entered #{a}"
end
To understand "each" you must first understand blocks. Every method in
ruby has an implicit optional argument which is a block of code. The
block is an anonymous function that is called by the method via the
"yield" statement. An example will make it clearer:
def run_a_block(arg1, arg2)
puts "Argument 1 was #{arg1}"
puts "Argument 2 was #{arg2}"
puts "Now going to run the block with arguments foo and 42"
yield ["foo", 42]
puts "Okay, the block has run, now we are back in the run_a_block method"
end
run_a_block("hello", "world") do |x, y|
puts "Now we are inside the block. run_a_block passed us arguments
#{x} and #{y}"
end
The "do |x,y| ... end" bit is the block. The |x, y| is the argument
list, and means that the calling method is expected to yield a list of
two values. When 'yield' is called, control passes from the calling
method to the block, and when it is done it returns to the line after
yield.
Okay, now for "each". "each" is a method of a collection. It expects a
block, and yields each element of the collection in turn to the block.
list = [1, 2, 4, 8, 16, 31]
list.each do |number|
puts "Got element #{number} from the list"
end
There is one more subtlety in _why's code example - when a block is
passed a list of several elements, it can either capture them as a
list or as individual elements (this is called "destructuring"). So if
we call each on a hash table, which yields [key, value] pairs, we can
say either
h = {"hello" => "world", "foo" => "bar", "baz" => "quux"}
h.each do |pair|
puts "key is #{pair[0]}"
puts "value is #{pair[1]}"
end
# or this way
h. each do |key, value|
puts "key is #{key}"
puts "value is #{value}"
end
martin
···
On Sun, Jun 6, 2010 at 12:50 PM, Kaye Ng <sbstn26@yahoo.com> wrote:
After I type a word (and press an 'OK' button?), then what? Can anyone
explain to me the role of Gets here? And also the Each block please. You
may also give me another example with Gets and Each.