Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does String(42) do in Ruby?

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?

like image 459
Samuel Danielson Avatar asked Dec 11 '25 04:12

Samuel Danielson


1 Answers

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.

like image 152
sepp2k Avatar answered Dec 13 '25 00:12

sepp2k