更好的我的代码版本 - 糟糕的切片

时间:2014-05-26 14:29:06

标签: ruby

我已经通过了测试,所以代码工作它真的看起来有点难看有点unRuby,有没有更多的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

2 个答案:

答案 0 :(得分:5)

1+(x-1)等于x

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

分配给@word无需通过测试。

答案 1 :(得分:4)

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

def start_of_word(word, x=1)
  @word = word.slice(1, x)
end