On May 17, 7:43 pm, John Merlino <li...@ruby-forum.com> wrote:
> I still dont think I am fully clear on the Class class role.
>
> For example:
>
> ruby-1.8.7-p330 :010 > class Class
> ruby-1.8.7-p330 :011?> def is_a?
> ruby-1.8.7-p330 :012?> puts 'a'
> ruby-1.8.7-p330 :013?> end
> ruby-1.8.7-p330 :014?> end
> => nil
> ruby-1.8.7-p330 :015 > A.is_a?
> a
> => nil
> ruby-1.8.7-p330 :016 > class A
> ruby-1.8.7-p330 :017?> def a_is_a
> ruby-1.8.7-p330 :018?> is_a?
> ruby-1.8.7-p330 :019?> end
> ruby-1.8.7-p330 :020?> end
> => nil
> ruby-1.8.7-p330 :021 > @a = A.new
> => #<A:0x1069b8460>
> ruby-1.8.7-p330 :022 > @a.a_is_a
> ArgumentError: wrong number of arguments (0 for 1)
>
> It says wrong number of arguments, despite there is nothing in argument
> list in method definition. a_is_a is a getter method. It returns a value
> returned by the class method is_a? defined in class Class. Since class A
> is a class, it should have access to class methods of Class (and it
> indeed works if you call the class method outside scope of instance
> method definition and within the scope of the class A). Or is this an
> issue of scope, where you cannot try to access a class method within an
> instance method? But then why does it throw error it does?
>
Your a_is_a is an instance method so is_a? is shorthand for self.is_a?
and in this case self is the instance of A, not A itself, so it's
calling the instance method is_a? that A inherits from Object, not the
one you defined on Class. That is_a? method requires an argument so
you get the expected error.
You seem to be conflating a certain class object responding to a
method and instances of that class responding to it.
Fred
> Thanks for response.
>
> --
> Posted viahttp://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
No comments:
Post a Comment