2

我在 ruby​​ 中有这个测试我正在尝试实现 require "silly_blocks"

describe "some silly block functions" do

  describe "reverser" do
    it "reverses the string returned by the default block" do
      result = reverser do
        "hello"
      end
      result.should == "olleh"
    end

    it "reverses each word in the string returned by the default block" do
      result = reverser do
        "hello dolly"
      end
      result.should == "olleh yllod"
    end
  end

这是方法

def do_reverse(str)
 str = str.split 
 first_str = str[0].reverse
 second_str= str[1]
 if (second_str == nil)
  str = first_str.to_s
 else
 second_str = str[1].reverse
 str = (first_str +" "+ second_str)
 end 
end 

我可以实现它的最佳方式是什么。当我尝试进行测试时它失败了,但是该方法本身会返回储备。我只是有点困惑。

4

5 回答 5

2

试试这个代码:

def reverser

   yield.split.map { |word| word.reverse}.join(" ")

end
于 2013-08-12T07:56:13.777 回答
1

这是一个简单的方法来做你正在寻找的东西,有规格。

# lib/reverse_words.rb
def reverse_words(phrase)
  return '' if phrase.nil?
  words = phrase.split
  phrase.split.map(&:reverse!).join(' ')
end

def reverser
  reverse_words(yield)
end

# spec/reverse_words_spec.rb
describe "#reverse_words" do
  context "when single word" do
    subject { reverse_words("hello") }
    it { should == "olleh" }
  end

  context "when multiple words" do
    subject { reverse_words("hello dolly") }
    it { should == "olleh yllod" }
  end

  context "when nil" do
    subject { reverse_words(nil) }
    it { should == '' }
  end

  context "when empty" do
    subject { reverse_words('') }
    it { should == '' }
  end

end

请注意,reverser规范只是利用了reverse_words已经指定通过的行为。

describe "#reverser" do
  subject do
    reverser do
      "this is a test"
    end
  end
  it { should == reverse_words("this is a test") }
end

这是一个不那么冗长的 reverse_words 规范:

describe "#reverse_words (less wordy)" do
  # counterintuitive keys as answers to support the nil case
  cases = { "olleh" => "hello",
      "olleh yllod" => "hello dolly",
      ''            => nil,
      ''            => ''
    }

  cases.each_pair do |expected, input| 
    context "#{input} should equal #{expected}" do
      subject { reverse_words(input) }
      it { should == expected }
    end
  end
end
于 2013-02-17T18:41:57.293 回答
0

所以。我也来这里寻找有关如何执行此操作的信息。因为语言不清楚。我去异地查看,找到了足够的信息来通过测试。

因此,块是花括号之间的东西,有时跟随 ruby​​ 中的函数,例如

list.each {|i| i.reverse}

所以规范正在做的是试图弄清楚当它发生时会发生什么:

rerverser {"hello"}

将 yield 放在函数中只会返回块中的任何内容,所以

def print_block
    puts yield
end

print_block {"Hello world."}

#=> "Hello world"

然后你可以像操纵任何参数一样操纵产量。块还有很多。这是一个很好的起点,但如果您到目前为止已经解决了所有 Test First 的 learn_ruby 练习,那么您就需要知道这些知识来解决该练习。

于 2014-09-17T17:43:34.897 回答
0

这行得通。您想要的数据存储在“yield”中。

def reverser
  yield.gsub(/\w+/) { |w| w.each_char.to_a.reverse.join }
end
于 2013-06-29T03:14:27.237 回答
0

我的逆向方法:

def reverser
    # yield is the string given in the block
    words = yield.split(' ')
    final = []
    words.each do |word|
        final.push(word.reverse)
    end
    final.join(' ')
end
于 2014-05-15T09:27:48.923 回答