ruby print或puts 打印数组元素问题
高洛峰
高洛峰 2017-04-22 09:00:16
0
1
892
a = [[1,2,3], [4,5,6], [7,8,9]]
a.each {|v| print v}
结果:
    [1,2,3][4,5,6][7,8,9]

a.each {|v| puts v}
结果:
    1
    2
    3
    4
    5
    6
    7
    8
    9

我知道print和puts差别
print打印出来,我可以了解!
但是 puts 打印出来,我不明白。
如果puts是会换行,如果换行应该打赢成这样吧!:

[1,2,3]
[4,5,6]
[7,8,9]

还有一个问题就是:
Ruby

a.each {|v| puts v[0]} # 1,4,7

Python

for i in a:
  print i[0] # [1,2,3]

each和for都一样,我已经测试了。但是我搞不清楚,为什么ruby结果是147而不是[1,2,3]呢?

谢谢解答!

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
刘奇

Correct to the first one, why is it not what you said, but the following:

[1,2,3]
[4,5,6]
[7,8,9]

First of all, let me ask you why you said this? Can you give yourself the answer?
puts outputs the content and then wraps it. Since one dimension is wrapped, why don't you wrap it in two dimensions?

2

a After adjusting each, there is a 1-dimensional array in the loop. Each time, the first element (subscript 0) in the one-dimensional array is taken, which is of course 1, 4, 7

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template