简体   繁体   中英

Override Ruby String class method

I'm new to Ruby and am trying to figure this out:

class SuperString < String
    def size
        "The Size: " + super.size.to_s
    end
end

a = SuperString.new("My String")
b = String.new("My String")
puts a.size
puts b.size

The output is:

"The Size: 8"
9

Why is one 8 and the other 9?

With SuperString.new("My String").size ,

  • super calls the method of the superclass, which is String#size , and will return 9 , which is the length of the string "My String" .
  • Next, 9.size will return 8 , which is the number of bytes used to represent Fixnum .
  • Finally, 8.to_s will return "8" .

With String.new("My String").size ,

  • size will return 9 , which is the length of the string "My String" .

It's because you called the method .size on the method .super, .super calls to the super class of your class SuperString ( String in this case ), for a method of the same name of the method that you're currently defining.

By calling .size on super you're actually calling .size on the return value of super ( Which is the size of "My String", which is 9 ).

Here's how you want to do the method

 class SuperString < String def size "The Size: " + super.to_s end end a = SuperString.new("My String") b = String.new("My String") a.size # => "The Size: 9" b.size # => 9 

an_string = "My String"

class SuperString < String
    def size
        x = super
        p x
        y = x.size
        p y
        z = y.to_s
        p z
        "The Size: " + z
    end
end

a = SuperString.new an_string
b = String.new an_string

puts a.size
p a
puts b.size
p b

outputs

9
8
"8"
The Size: 8
"My String"
9
"My String"

So then I tried:

Ezekiels-MacBook-Pro:/Users/tehgeekmeister| irb
1.9.3p327 :001 > 9.size
 => 8 
1.9.3p327 :002 > 8.size
 => 8 
1.9.3p327 :003 > 7.size
 => 8 
1.9.3p327 :004 > 256.size
 => 8 
1.9.3p327 :005 > 1000000000000000000000000000.size
 => 12 

Basically, 8 is the size of the integer that represents the size. It's using 8 bytes. =P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM