i wrote a ruby script and executed it, here are the lines and the results:
puts 3.to_s + ‘b’ # => 3b
puts (3).to_s + ‘b’ # => 3
puts ((3).to_s + ‘b’) # => 3b
i am confused about that.
i tried that in irb also and i got
i wrote a ruby script and executed it, here are the lines and the results:
puts 3.to_s + ‘b’ # => 3b
[1] equivalent to: (puts(3.to_s + ‘b’))
puts prints out expression 3.to_s + ‘b’ converted to String, that is ‘3b’.
puts (3).to_s + ‘b’ # => 3
[2] equivalent to: (puts(3)).to_s + ‘b’)
puts prints out expression 3 converted to String, that is ‘3’. Then
expression nil.to_s + ‘b’ is being evaluated (nil is the return value of
puts). There’s neither variable assignment nor another puts for the last
evaluation, so it is just discarded.
puts ((3).to_s + ‘b’) # => 3b
[3] Same as [1]
i am confused about that.
i tried that in irb also and i got
(3).to_s + ‘b’
=> “3b”
By default irb prints out the result of an input expression with ‘p’, so
this is roughly equivalent to explicit expression
p ((3).to_s + ‘b’)
This looks like case [3] doesn’t it
but
puts (3).to_s + ‘b’
3
=> “b”
And this looks like case [2] plus previously discarded value ‘b’ is printed
out with ‘p’ (again, default irb behaviour).
···
----- Original Message -----
From: “Meinrad Recheis” meinrad.recheis@aon.at
Newsgroups: comp.lang.ruby
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Monday, March 24, 2003 11:19 AM
Subject: [puts] - bug or feature?
i wrote a ruby script and executed it, here are the lines and the results:
puts 3.to_s + ‘b’ # => 3b
3.to_s == “3”, to which you add ‘b’, and then you print the whole
result (“3b”). So it’s like:
puts ((3.to_s) + ‘b’)
puts (3).to_s + ‘b’ # => 3
This calls puts(3), the return value of which is nil. nil.to_s is “”,
which gets added to ‘b’. You haven’t asked it to print that result,
so it just gets discarded. (But that’s why you get “b” as the
expression’s value when you do the same expression in irb.)
So that one is like:
((puts 3).to_s) + ‘b’
puts ((3).to_s + ‘b’) # => 3b
Here you’re evaluating the expression and then printing it,
including the ‘b’.
At Tue, 25 Mar 2003 04:19:29 +0900, Meinrad Recheis wrote:
i wrote a ruby script and executed it, here are the lines and the results:
puts 3.to_s + ‘b’ # => 3b
puts (3).to_s + ‘b’ # => 3
puts ((3).to_s + ‘b’) # => 3b
This behavior is changed in 1.7 or later, and all print “3b”.
This calls puts(3), the return value of which is nil. nil.to_s is “”,
which gets added to ‘b’. You haven’t asked it to print that result,
so it just gets discarded. (But that’s why you get “b” as the
expression’s value when you do the same expression in irb.)