Forum: Ruby Class.new and class keyword not the same?

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.
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Thomas Sawyer (7rans)
on 2008-11-14 17:13
(Received via mailing list)
Here the normal scenario:

  class X
    def self.inherited(s)
      p "here"
    end
  end

  class Z < X
    p "race"
  end

result:

  "here"
  "race"

But in a test case of mine I need the class to be a variable, but:

  z = Class.new(X) do
    p "race"
  end

result:

  "race"
  "here"

Why is "race" coming before "here"?

ruby 1.8.6 (2007-09-24 patchlevel 111) [x86_64-linux]

T.
1bac2e65d64faf472cf2ebc94f0f5ee0?d=identicon&s=25 Ara Howard (ahoward)
on 2008-11-14 17:23
(Received via mailing list)
On Nov 14, 2008, at 9:09 AM, Trans wrote:

>  end
>  end
> T.
>



dunno why - but the fix is

cfp:~ > cat a.rb
class X
   def self.inherited(s)
     p "here"
   end
end


z = Class.new(X)
z.class_eval do
   p "race"
end


class Z < X
   p "race"
end



cfp:~ > ruby a.rb
"here"
"race"
"here"
"race"




a @ http://codeforpeople.com/
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2008-11-15 16:09
(Received via mailing list)
On Fri, Nov 14, 2008 at 5:09 PM, Trans <transfire@gmail.com> wrote:
>  end
>  end
> T.
>
>

Strange, it is "fixed" in 1.9 (though I have an old version ruby 1.9.0
(2008-06-20 revision 17482) [i486-linux]
). But  but then Jruby behaves like 1.8, maybe this is defined
somewhere?
If we look at the warning below it really seems like a bug, 'cause the
old method is *not* discarded.

516/16 > cat xxx.rb && ruby1.9 -v xxx.rb && ruby -v xxx.rb && jruby -v
xxx.rb
class X
  def self.inherited(x);
    x.send :define_method, :a do puts 42 end
  end
end
class Y < X
  def a; puts "21*2" end
end
Y::new.a
puts "-"*72
Class::new Y do
  def a; puts "222.to_i(4)" end
end::new.a
ruby 1.9.0 (2008-06-20 revision 17482) [i486-linux]
xxx.rb:11: warning: method redefined; discarding old a
21*2
------------------------------------------------------------------------
xxx.rb:16: warning: method redefined; discarding old a
222.to_i(4)
ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-linux]
xxx.rb:11: warning: method redefined; discarding old a
21*2
------------------------------------------------------------------------
42
ruby 1.8.6 (2008-05-30 rev 6360) [i386-jruby1.1]
21*2
------------------------------------------------------------------------
42

Any views on this?

Cheers
Robert
This topic is locked and can not be replied to.