Forum: Ruby Accessing a class method from within a base class

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Nick (Guest)
on 2006-05-27 20:24
Hi,

When I run the code at the end of the message it all works as expected
but I get a warning :

workpad2.rb:3: warning: Object#type is deprecated; use Object#class

This is casued by the first line in the BaseClass.initialize method,
because I use the type property to get to actual type of the class
instance.  If I use the "class" property as suggested in the warning,
the code actually fails to compile with the following :

workpad2.rb:3: parse error, unexpected '.'
		if(!class.isMatch(input))
		          ^
This occurs when I change the initialize method to use the "class"
accessor:

	def initialize(input)
		if(!class.isMatch(input))
			raise "Invalid input provided"
		end
	end

Any advice? Should I just ignore the warning and go-ahead and use the
"type" accessor?

Nick.



The code is:

class BaseClass
	def initialize(input)
		if(!type.isMatch(input))
			raise "Invalid input provided"
		end
	end
end

class AClass < BaseClass
	def initialize(input)
		super(input)
	end

	def self.isMatch(input)
		puts "AClass::invoked"
		input =~ "1"
	end
end

class BClass < BaseClass
	def initialize(input)
		super(input)
	end
	def self.isMatch(input)
		puts "BClass::invoked"
		input == "2"
	end

end

bclass = BClass.new("2")
puts "here"
unknown (Guest)
on 2006-05-27 21:00
(Received via mailing list)
On May 27, 2006, at 12:24 PM, Nick wrote:
> If I use the "class" property as suggested in the warning,
> the code actually fails to compile with the following :
>
> workpad2.rb:3: parse error, unexpected '.'
> 		if(!class.isMatch(input))

You have to write this as:

   if (!self.class.isMatch(input))


The reason is simply because the parser thinks 'class' all by itself
is an attempt to open a class block as in:

class Foo
   #
end

by using self.class instead the parser sees it as a method call.  It
is an unfortunate syntax ambiguity that has to be manually
disambiguated to avoid the error.

Gary W.
Nick (Guest)
on 2006-05-27 21:47
unknown wrote:
> On May 27, 2006, at 12:24 PM, Nick wrote:
...
> You have to write this as:
>
>    if (!self.class.isMatch(input))

Gary,

I could have sworn I tried that! Its working now.  I've been coding
since 1pm so I guess I took a break at the right time, right after
posting the message.

Many thanks,

Nick.
This topic is locked and can not be replied to.