2014-08-30 67 views
0

我不能告诉什么是错我的代码:调用特定的元素没有返回(红宝石)

def morse_code(str) 
    string = [] 
    string.push(str.split(' ')) 
    puts string 
    puts string[2] 
end 

我很期待是,如果我用“什么是狗”的海峡,我会得到如下结果:

=> ["what", "is", "the", "dog"] 
=> "the" 

但我得到的却是零。如果我做了字符串[0],它只是给了我整个字符串。 .split函数是否将它们分解为不同的元素?如果任何人都可以提供帮助,那会很棒。感谢您抽出时间来阅读。

回答

2

你的代码应该是:

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的数组。因此,如果你想访问像12等任何索引..,你会得到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"]] 

随着Arrayputsp作品完全不同方式。我总是不好阅读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::putsKernel::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