你的代码应该是:
def morse_code(str)
string = []
string.push(*str.split(' '))
puts string
p string[2]
end
morse_code("what is the dog")
# >> what
# >> is
# >> the
# >> dog
# >> "the"
str.split(' ')
是给["what", "is", "the", "dog"]
,你正在推动这个阵列对象数组串。因此string
成为[["what", "is", "the", "dog"]]
。因此string
是大小为1
的数组。因此,如果你想访问像1
,2
等任何索引..,你会得到nil
。您可以使用p
(它在阵列上调用#inspect
)来调试它,但不是puts
。
def morse_code(str)
string = []
string.push(str.split(' '))
p string
end
morse_code("what is the dog")
# >> [["what", "is", "the", "dog"]]
随着Array
,puts
比p
作品完全不同方式。我总是不好阅读MRI代码,因此我看看Rubinious代码。看看他们如何定义IO::puts
,这与MRI相同。现在看specs for the code
it "flattens a nested array before writing it" do
@io.should_receive(:write).with("1")
@io.should_receive(:write).with("2")
@io.should_receive(:write).with("3")
@io.should_receive(:write).with("\n").exactly(3).times
@io.puts([1, 2, [3]]).should == nil
end
it "writes nothing for an empty array" do
x = []
@io.should_receive(:write).exactly(0).times
@io.puts(x).should == nil
end
it "writes [...] for a recursive array arg" do
x = []
x << 2 << x
@io.should_receive(:write).with("2")
@io.should_receive(:write).with("[...]")
@io.should_receive(:write).with("\n").exactly(2).times
@io.puts(x).should == nil
end
我们现在可以肯定的是,IO::puts
或Kernel::puts
的行为与阵列就是这个样子,因为Rubinious人实现了它。你现在可以看看MRI代码。我刚刚找到了MRI one,看看the below test
def test_puts_recursive_array
a = ["foo"]
a << a
pipe(proc do |w|
w.puts a
w.close
end, proc do |r|
assert_equal("foo\n[...]\n", r.read)
end)
end