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

gotnix · 2015年09月07日 · 最后由 lazybios 回复于 2015年09月08日 · 2143 次阅读
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;
}
需要 登录 后方可回复, 如果你还没有账号请 注册新账号