Why cant I do this?
>> s = String
>> s(42)
s(42)
NoMethodError: undefined method `s' for main:Object
from (irb):86
from /home/sam/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
Next.
>> String.new 42
String.new 42
TypeError: can't convert Fixnum into String
from (irb):90:in `initialize'
from (irb):90:in `new'
from (irb):90
from /home/sam/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
How does String() convert a Fixnum to a String if String.new cannot? I assume String() calls to_s. But then what is String.new looking for besides a string to copy? Is new an alias for dup?
The reason that s(42) does not work in your example, is that there is a constant named String (which points to the class) as well as a method named String (which converts the argument to a string using to_s). When you do s = String, s will now point to the same class as String. However when you call s(42), ruby will look for a method named s, which does not exist and you get an error.
The key here is that in ruby there can be a variable or constant and a method with the same name without them having anything to do with each other.
The reason for the differing behaviour between String(42) and String.new(42) is that String calls to_s and String.new calls to_str.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With