Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 我的代码的更好版本-错误的切片_Ruby - Fatal编程技术网

Ruby 我的代码的更好版本-错误的切片

Ruby 我的代码的更好版本-错误的切片,ruby,Ruby,我已经通过了测试,所以代码可以正常工作。它看起来确实有点难看,有点不可靠。有没有一种更适合Ruby的方法呢 这是我的解决方案 def start_of_word(word, x=1) @word = word[0,1+(x-1)] end 这些都是要通过的测试 describe "start_of_word" do it "returns the first letter" do start_of_word("hello", 1).should == "h"

我已经通过了测试,所以代码可以正常工作。它看起来确实有点难看,有点不可靠。有没有一种更适合Ruby的方法呢

这是我的解决方案

 def start_of_word(word, x=1)
      @word = word[0,1+(x-1)]
 end
这些都是要通过的测试

describe "start_of_word" do
    it "returns the first letter" do
      start_of_word("hello", 1).should == "h"
    end

    it "returns the first two letters" do
      start_of_word("Bob", 2).should == "Bo"
    end

    it "returns the first several letters" do
      s = "abcdefg"
      start_of_word(s, 1).should == "a"
      start_of_word(s, 2).should == "ab"
      start_of_word(s, 3).should == "abc"
    end
  end

您已经重新实现了
slice
。它接受起始索引和长度:

def start_of_word(word, x=1)
  @word = word.slice(1, x)
end
1+(x-1)
等于
x

def start_of_word(word, x=1)
  word[0, x]
end

通过测试不需要分配给
@word

尝试完整性-在rails中,您只需执行
word。首先(x)
它应该是
word.slice(0,x)
,即可通过测试。