Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't these string expressions print the same result?

Tags:

ruby

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?

like image 938
S H Avatar asked Sep 04 '26 00:09

S H


2 Answers

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

like image 31
CoupDeMistral Avatar answered Sep 05 '26 15:09

CoupDeMistral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!