On Oct 3, 2006, at 11:07 AM, Tomasz W. wrote:
Then could you explain, whether:
These are probably questions better asked of irb, but I’ll try…
a = Name.new(‘foo’, ‘bar’)
a.instance_eval { a.sortable } # correct or not ?
I have no idea what “correct” means here, but I can tell you that
Ruby allows protected methods to be called function-style for the
current object and method style for another object of the same class:
a.instance_eval { a.sortable } # correct or not ?
NoMethodError: protected method `sortable’ called for #<struct Name
first=“foo”, last=“bar”>
from (irb):20
from (irb):20
from :0a.instance_eval { sortable }
=> [“bar”, “foo”]a.instance_eval { self.sortable }
NoMethodError: protected method `sortable’ called for #<struct Name
first=“foo”, last=“bar”>
from (irb):23
from (irb):23
from :0
You do seem to be able to use either style in method definitions for
the current object though:
class Name < Struct.new(:first, :last)
def full
“#{first} #{last}”
end
?> def last_first
"#{last}, #{first}"
end
?> def sortable
[last, first]
end
protected :sortable
?> def <=>(other)
self.sortable <=> other.sortable
end
end
=> nilName.new(“James”, “Gray”) <=> Name.new(“Dana”, “Gray”)
=> 1
Name.instance_eval { a.sortable } # correct or not ?
Well, it blows up and I consider that “correct”, yes. You are inside
the Name class here, not an instance of that class.
James Edward G. II