From: Marnen Laibow-Koser Date: 2009-11-15T23:13:30+09:00 Subject: Re: what's || Ralph Shnelvar wrote: > 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. It declares block arguments. See the sections in the Pickaxe Book on blocks. > > 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. Right. > > 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". Right. > > - - - > > Now here's where I get vaguer. > > "upto" is a method that, in turn, can call subroutines. Blocks -- "subroutine" is not a Ruby term. > One of the > subroutines it can call is ... > do |c| print c," " end It can call any block at all. > > 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. Correct. > > The subroutine > do |c| print c," " end > will see that parameter as c Also correct. > > 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. No. The block has to know that upto will yield it one object. That's all it has to know. > That is, it has to know a fair > bit about the public interface of "upto" and what "upto" is supposed > to do. Nope. The block expects one object. It doesn't really care whether it's being yielded to from 1.upto(10), or ['e', 'd', :c, {:b => 3957}].each, or anything else that will yield it one object (of any kind) as an argument. In fact, you could store the block in a variable and yield to it from each of those methods in turn. > Internal implementation of "upto" is, of course, nearly > irrelevant. Totally irrelevant, actually. > > 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 You're right that those are equivalent, but it has nothing to do with your statement about parameters and arguments. > > > > I hope this helps. Best, -- Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org -- Posted via http://www.ruby-forum.com/.