从数组中调用特定元素不返回(Ruby)

时间:2014-08-30 05:57:40

标签: ruby arrays

我无法说出我的代码有什么问题:

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

我期待的是,如果我使用"什么是狗"对于str,我会得到以下结果:

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

但我得到的却是零。如果我做字符串[0],它只会再次给我整个字符串。 .split函数不会将它们分解为不同的元素吗?如果有人可以提供帮助,那就太好了。感谢您抽出宝贵时间阅读本文。

1 个答案:

答案 0 :(得分: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 。因此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 ,看看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