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

say*_*yth 0 ruby

我已经通过了测试,所以代码工作它真的看起来有点难看有点unRuby,有没有更多的Ruby方式.

这是我的解决方案

 def start_of_word(word, x=1)
      @word = word[0,1+(x-1)]
 end
Run Code Online (Sandbox Code Playgroud)

这些都是通过的考验

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
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 5

1+(x-1)是等于x.

def start_of_word(word, x=1)
  word[0, x]
end
Run Code Online (Sandbox Code Playgroud)

分配给@word没有必要通过测试.