Extending classes and instances

This question has two parts.

The Ruby programming language book provides an example (section 8.1.1) about extending a string object and class using a module.

First question. Why, if you extend a class with a new method and then create an object / instance of this class, you cannot access this method?

irb(main):001:0> module Greeter; def ciao; "Ciao!"; end; end
=> nil
irb(main):002:0> String.extend(Greeter)
=> String
irb(main):003:0> String.ciao
=> "Ciao!"
irb(main):004:0> x = "foo bar"
=> "foo bar"
irb(main):005:0> x.ciao
NoMethodError: undefined method `ciao' for "foo bar":String
        from (irb):5
        from :0
irb(main):006:0>

Second part. When I try to extend the Fixnum object, I get an undefined method error. Can someone explain why this works for a string but not fixnum?

irb(main):045:0> module Greeter; def ciao; "Ciao!"; end; end
=> nil
irb(main):006:0> 3.extend(Greeter)
TypeError: can't define singleton
        from (irb):6:in `extend_object'
        from (irb):6:in `extend'
        from (irb):6
+5
source share
2 answers

. , / class, ?

String, #ciao - , .

String.send(:include, Greeter)
x = "foo bar"
x.ciao
# => "Ciao!"

, Fixnum, undefined . - , , Fixnum?

.

"Fixnums, Symbols, true, nil false . , , .

Singleton . , () Fixnum " " " "- . ".

, / Fixnum, Fixnum Mixin. , Rails/ActiveSupport,

3.days.ago
1.hour.from_now
+9

obj.extend(module) module obj. String.extend(Greeter), Greeter Class, String.

- . :

class String
  include Greeter
end

class String
  def ciao
    "Ciao!"
  end
end

Fixnums ( , true, false nil) - . Fixnums . Ruby .

, , , :

t = "Test"
t.extend(Greeter)
t.ciao
=> "Ciao!"
+2

All Articles