join two strings in ruby

There are several ways to join two strings in Ruby:

  1. Using the + operator:
main.rb
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
puts result # output: "Hello World"
93 chars
5 lines
  1. Using string interpolation:
main.rb
str1 = "Hello"
str2 = "World"
result = "#{str1} #{str2}"
puts result # output: "Hello World"
93 chars
5 lines
  1. Using the concat method:
main.rb
str1 = "Hello"
str2 = "World"
str1.concat(" #{str2}")
puts str1 # output: "Hello World"
88 chars
5 lines
  1. Using the << operator:
main.rb
str1 = "Hello"
str2 = "World"
str1 << " " << str2
puts str1 # output: "Hello World"
84 chars
5 lines
  1. Using the join method:
main.rb
str1 = "Hello"
str2 = "World"
result = [str1, str2].join(" ")
puts result # output: "Hello World"
98 chars
5 lines

gistlibby LogSnag