What does String (42) do in Ruby?

Why can't 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>'

Further.

>> 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 Fixnum to String if String.new can't? I assume String () calls to_s. But then, what does String.new look for besides the string to copy? Is the new alias for dup?

+3
source share
2 answers

, s(42) , , String ( ), String ( to_s). s = String, s , String. , s(42), ruby ​​ s, .

, ruby ​​ , .

String(42) String.new(42) , String to_s String.new to_str.

+6

"42", s = "42" - , .

Fixnum, , s = some_fixnum.to_s .

0

Source: https://habr.com/ru/post/1789897/


All Articles