Ruby - String String Concatenation

Introduction

You can concatenate strings using << or + or just by placing a space between them.

Here are three examples of string concatenation; in each case, s is assigned the string "Hello world":

Demo

s = "Hello " << "world" 
puts s# ww  w . ja  v  a2 s  . c  o m

s = "Hello " + "world" 
puts s

s = "Hello "  "world" 
puts s

Result

When using the << method, you can append Fixnum integers (in the range 0 to 255) to string.

Those integers are converted to the character with that character code.

Character codes 65 to 90 are converted to the uppercase characters A to Z, 97 to 122 are converted to the lowercase a to z.

Other codes are converted to punctuation, special characters, and non-printing characters.

To print the number itself, you must convert it to a string using the to_s method.

The to_s method is obligatory when concatenating Fixnums using the + method or a space.

The following program prints out characters and numeric codes for values between 0 and 126, which include the standard Western alphanumeric and punctuation characters:

Demo

i = 0 
begin # from   ww w . ja v a  2 s .c  om
    s = "[" << i << ":" << i.to_s << "]" 
    puts(s)  
    i += 1 
end until i == 126 

s1 = "This " << "is" << " a string " << 36 # char 36 is '$' 
s2 = "This "  + "is" + " a string "  + 36.to_s 
s3 = "This "  "is"  " a string "  + 36.to_s 

puts("(s1):" << s1) 
puts("(s2):" << s2) 
puts("(s3):" << s3)

Result

Related Topic