Introduction
We use puts, print, and p to show messages on the screen, but they do it in slightly different ways.
We use puts, print, and p to show messages on the screen, but they do it in slightly different ways.
puts value print value p value
puts adds a new line after the output.print does not add a new line.p shows the value in a way that helps debugging (like showing quotes around strings).puts "Hello" puts "World"
print "Hello" print "World"
p "Hello" p "World"
This program shows how puts, print, and p behave differently when printing.
puts "Hello" print "World" p "!"
puts automatically adds a new line, so each call appears on its own line.
print keeps printing on the same line unless you add a new line character \n yourself.
p is useful for debugging because it shows the exact form of the value, including quotes for strings.
puts prints with a new line.
print prints without a new line.
p prints the value in a way that helps you see its exact form.
puts and print in Ruby?puts behaviorputs prints the given value and adds a new line automatically after it.print behaviorprint prints the given value but does not add a new line after it.puts adds a new line after output, print does not. -> Option Aputs adds newline = C [OK]print prints without adding a newline.print "Hello" is correct syntax; puts adds newline, p prints inspect form, and puts(Hello) is invalid because Hello is not a string.puts "Hi" print "There" p "!"
puts "Hi"print "There"p "!"p prints the inspect form of the string, which includes quotes, and adds a newline. So it prints "!" with quotes and a newline.puts ["1", "2", "3"]What is the best fix?
puts ["1", "2", "3"] outputputs prints each element on a new line without quotes, so output is:
1
2
3
p to print with quotes and inspect formp ["1", "2", "3"] prints the array as it is, including brackets and quotes if strings, with a newline.puts with p -> Option Cputs [["1", "2"], ["3", "4"]]print [["1", "2"], ["3", "4"]]p [["1", "2"], ["3", "4"]]p prints the inspect form, showing quotes if strings and the full structure on one line, exactly as the array looks.puts [["1", "2"], ["3", "4"]].to_sPass the test and this pattern moves unknown