How to concatenate byte in Ruby

In Programming Ruby Second Edition (1.8), page 124, there is an example said

str2=""; str2 << 1 << 2 << 3 ; will produce "010203".

I've tried it in irb and have got this result, but just one time. When I tried to do it again, and again, and it never occurred. Can anyone pls tell me why?

BTW, my environment is in ruby 2.0.0p353 (2013-11-22 revision 43784) [x86_64-linux]

     ->   irb
 irb(main):001:0> str2 = ""
 => ""
 irb(main):002:0> str2 << 1 << 2 <<3
 => "u0001u0002u0003"
 irb(main):003:0> str1 = ""
 => ""
 irb(main):004:0> str1 <<1
 irb(main):005:0" str1
 irb(main):006:0" str1 << 1
 irb(main):007:0" str1
 irb(main):008:0" str1 << 1 << 2
 irb(main):009:0" str1
 irb(main):010:0" str1 << 1 << 2 << 3
 irb(main):011:0" str1
 irb(main):012:0" 

You shoud add space between << and 1 .

str1 << 1
       ^

Otherwise, that line is considered as the beginning of the heredoc.


You just need a space after the << operator and 1 .

As your code stands now this looks like the beginning of a heredoc.

链接地址: http://www.djcxy.com/p/95418.html

上一篇: 如何格式化持续时间ISO 8601(PT45S)

下一篇: 如何连接Ruby中的字节