为什么这个表达式:
puts "abc" * 5
=> " abcabcabcabcabc"
不等于这个表达式?
5.times do puts "abc"
ABC
ABC
ABC
ABC
ABC
=> 5
你能解释为什么他们不打印相同的结果吗?
答案 0 :(得分:6)
第一次将字符串“abc”连接到自身五次:
"abc"*5 = "abc"+"abc"+"abc"+"abc"+"abc" = "abcabcabcabcabc"
第二段代码使用puts函数写入“abc”5次。 puts函数在每条消息之后写一个换行符,这意味着它写了“abc \ n”5次。
5.times do puts "abc"
转向
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
答案 1 :(得分:1)
你可以用put替换puts,这不会在最后添加新行
5.times do print "abc"
end
abcabcabcabcabc => 5