Sunday, November 15, 2009, 5:59:31 AM, you wrote:
d> sorry just was learning ruby so have some low level questions,
d> in this statement:
d> 1.upto(10) do |c| print c," " end
d> what's the usage of "| ... |" in ruby? can't easily understand.
d> Thanks.
I'm just learning Ruby, too .. and I found this fairly tough to wrap
my head around. This is what I think I know:
Almost EVERYTHING in Ruby is an object. Thus the "1" in "1.upto(10)" is an
object.
Object have methods that can be applied to them. Or, equivalently,
objects can have messages sent to them. "upto" is method that can be
applied to the integer 1.
"upto" tokes an argument "10".
- - -
Now here's where I get vaguer.
"upto" is a method that, in turn, can call subroutines. One of the
subroutines it can call is ...
do |c| print c," " end
The object.method known as 1.upto(10) will call the subroutine
do |c| print c," " end
ten times.
Each time it calls
do |c| print c," " end
it will pass a parameter to the subroutine. In this case it will pass
1 the first time, 2 the second time ... 10 the last time.
The subroutine
do |c| print c," " end
will see that parameter as c
Thus, the subroutine
do |c| print c," " end
has to know a fair bit about the method "upto" in order to know what
"upto" will pass to the subroutine. That is, it has to know a fair
bit about the public interface of "upto" and what "upto" is supposed
to do. Internal implementation of "upto" is, of course, nearly
irrelevant.
Like in most high level languages, the names of the parameters and the
arguments do not have to be the same. Thus,
do |c| print c," " end
is exactly equivalent to
do |parm| print parm," " end
I hope this helps.