"abcabcabcabcabc" not equal t...">

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

Why is this expression:

puts "abc" * 5

      

=> "abcabcabcabcabc"

not equal to 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?

+3


source to share


2 answers


The first one writes the string "abc", concatenated to itself five times:

"abc"*5 = "abc"+"abc"+"abc"+"abc"+"abc" = "abcabcabcabcabc"

      

The second part of the code writes "abc" using puts 5 times. The puts function writes a newline character after each message, which means it writes "abc \ n" 5 times.



5.times do puts "abc"

      

turns into

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

      

+6


source


you can replace puts with a print that doesn't add a newline to the end

5.times do print "abc"
end

      



abcabcabcabcabc => 5

+1


source







All Articles