Peña, Botp wrote:
On their case, they like the @@ solution, except that they want the @@
removed. I thought i was so close here. I was looking for something like
var_missing or whatever and do what like debuggers do in reflection to get
into the local var...
I guess i made a mistake in that i was trying to _lure_ them rather than
educate them.
Good observation. Unfortunately, in order to get them over, it sounds like you'd have to teach them good programming practices, as Ruby's syntax/semantics encourage good practices and discourages bad ones. For example, in the problem you provided, the best solution (ignoring other factors such as deadlines) would have been to refactor the code to pass 'foo' as a parameter (in that case, no @ or $), or to objectize the code, and make it an instance variable of some object (a single @).
This works just fine, for example, and looks quite pretty to me:
#prints each member. takes any object that responds to #each,
#and whose elements respond to #inspect.
def print_each(arr)
arr.each {|f| p f}
end
letters=["a","b","c"]
print_each letters
__END__
But I could be alone.
This is with an instance variable, but it's overkill in this example, since we're not modifying foo:
#prints each member. constructor takes any object that responds to #each,
#and whose elements respond to #inspect.
class EachPrinter
def initialize(arr)
@arr = arr
end
def print
@arr.each {|f| p f}
end
end
letters=%w{a b c}
EachPrinter.new(letters).print
__END__
Here's another way possible in Ruby:
class Enumerable
#prints each element using Kernel#p
def p_each
self.each {|f| p f}
end
end
letters=%w{a b c}
letters.p_each #possible since letters.is_a? Enumerable
But decide for yourself whether you want to pollute the Enumerable method namespace. Since this is a general functionality that has nothing specifically to do with your problem domain, I'd opt for throwing it in.
Are any of these solutions valid for you? Is there something I'm missing?
Devin