Simple Newbie question. I kind of understand this whole block thing.
3.times {|i| puts i}
Bassically this is similar to
a for statement in other languages.
What throws me off is the
something do |line| #process something and line here
end
Is this correct? You take some object named something and process it’s values in the do-end statement using the variable list??
Also, the yield callback gets kind of confusing. I guess the examples I’ve seen have to be followed real closely. But yield calls the block to do some value manipulation?
I’ll try to dig up an example of what is confusing me to help demonstrate my confusion of yield.
Well, the method Integer#times iterate self times (3 in your case) and for
each iteration call the block, given it the current value.
This method can be written (very badly)
class Fixnum
def times
i = 0
while i < self
yield i
i += 1
end
end
end
something do |line| #process something and line here
end
Is this correct? You take some object named something and process it's
values in the do-end statement using the variable list??
not really, `something' is a method and this method call the block with
some value.
For example if you want to read a file, you write
IO.foreach('file') do |line|
# do something with line
end
the method IO::foreach open the file given in argument, read each line and
call the block, given it the current line. At the end, IO::foreach close
the file
But yield calls the block to do some value manipulation?
yield call the block with some values, and the block make some computation
with these values
The curly brackets and do..end are actually identical (apart from their
precedence when being parsed). So you can write either:
3.times {|i| puts i}
or
3.times do |i|
puts i
end
In both cases, you are calling method "times" of the number 3, and passing a
block of code. The number 3 executes this code block 3 times. On each
iteration it replaces |i| with the index value, from 0 to 2.
[Note that although irb shows "0 1 2 3", the loop is only executed three
times with indexes of 0 to 2. 3 is the final value returned by the
expression, and irb prints it]
The idea of a number doing work for you might seem like a strange way of
doing things, but it gets clearer when you ask an Array to execute some code
for each of its elements:
a=["hello","to","you"]
a.each {|i| puts i}
Other objects respond to 'each', including Range, which gives you something
closer to a for loop: