Steven Aguilar Steven Aguilar - 2 months ago 8
Ruby Question

Add two variables such that they become a String with a space between in Ruby

So i am trying to output in the same line two string variables with a space but I am getting the following error:


in `+': no implicit conversion of Fixnum into String (TypeError)


for the following code

puts s1 + " " + s2


How can I fix this code to print the value of string variable s1 with a space and the value of string variable s2 on the same line? for example

s1 = "hello" s2="world" output "Hello world"

Answer

You can do it with the following:

puts "#{s1} #{s2}"

and:

puts [s1, s2].join(" ")

Here are the following examples implemented code snippets above:

s1, s2 = "hello", "world"
puts "#{s1} #{s2}"
=> "hello world"

puts [s1, s2].join(" ")
=> "hello world"