Why does this expression:
puts "abc" * 5
=> "abcabcabcabcabc"
not equal this expression?
5.times do puts "abc"
abc
abc
abc
abc
abc
=> 5
Could you please explain why they don't print the same result?
The first writes the string "abc" concatenated to itself five times:
"abc"*5 = "abc"+"abc"+"abc"+"abc"+"abc" = "abcabcabcabcabc"
The second piece of code writes "abc" using the puts function 5 times. The puts function writes a newline character after each message, meaning that it writes "abc\n" 5 times.
5.times do puts "abc"
turns to
puts "abc" ->also jumps to the next line
puts "abc" ->also jumps to the next line
puts "abc" ->also jumps to the next line
puts "abc" ->also jumps to the next line
puts "abc" ->also jumps to the next line
you can replace puts with print, which doesn't add the new line at the end
5.times do print "abc"
end
abcabcabcabcabc => 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With