MenTaLguY
1/4/2006 5:25:00 PM
Quoting John Maclean <info@jayeola.org>:
> In this line of code can anyone tell me why "food" is a method? I
> thought that they are preceded by a dot.
>
> __ an array __ the method __ parameters for code
> block
> / / /
> [cornflakes, yam, rice].each { |food| eat food}
> / > code block __/ \__block args
>
Within the context of the block, "food" is a variable. "eat",
however, will be interpreted as a private method call (i.e. as a
call to the "eat" method on self), provided an "eat" variable does
not already exist in that scope.
Generally, given a bare identifier, the rule is:
1. If a previous assignment to the name exists in the current scope
(whether or not it was actually performed), the name is a variable
(or a parse error if you try to give it parameters)
2. otherwise, it is a call to a private method on self
Examples:
1. foo # method
2. foo = 1
foo # variable
3. if false
foo = 1 # never executed
end
foo # still a variable (initialized to nil)
4. [1, 2, 3].each { |foo| # introduced as block param
foo # variable here
}
foo # method call here
5. foo = 1
foo # variable
[1, 2, 3].each { |foo| # same variable
foo # yes, same variable
}
foo # still same variable
-mental