新手问题 puts 和 print 打印数组元素的区别?

gotnix · September 07, 2015 · Last by lazybios replied at September 08, 2015 · 2144 hits
arry = ['a1', ['b1', 'b2'], ['c1', 'c2', 'c3'], 'd1']

arry.each {|v| print "#{v}\n"}
a1
["b1", "b2"]
["c1", "c2", "c3"]
d1

arry.each {|v| puts v}
a1
b1
b2
c1
c2
c3
d1

很多地方都说 puts 和 print 的区别就是 puts 会在字符串后面追加换行符, 为什么遍历数组的时候不是这样呢?

是的,puts 会判断参数是否为数组,如果是的话 puts a 相当于 puts *a

安装 pry-doc, 然后

show-method $stdout.puts

可以看到其 C 实现

ruby 也可以数组解构?

puts==put string 吧,可以用 puts v.inspect

#1 楼 @luikore 应该是这段吧

if (rb_exec_recursive(io_puts_ary, argv[i], out)) {
    continue;
}
You need to Sign in before reply, if you don't have an account, please Sign up first.