一个rspec测试在ruby中的实现问题
我正在尝试用ruby实现这个测试 需要“愚蠢的块” 方法是这样的一个rspec测试在ruby中的实现问题,ruby,block,Ruby,Block,我正在尝试用ruby实现这个测试 需要“愚蠢的块” 方法是这样的 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 我
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
我能实现它的最佳方式是什么。当我尝试rake测试时,它失败了,但是该方法本身返回了保留。我只是有点困惑。这里有一个简单的方法,可以通过规范完成您想要的任务
# 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
spec只是利用了reverse\u words
已经被指定通过的行为
describe "#reverser" do
subject do
reverser do
"this is a test"
end
end
it { should == reverse_words("this is a test") }
end
这里有一个不太冗长的反向单词规范:
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
这很有效。您需要的数据存储在“yield”中 请尝试以下代码:
def reverser
yield.split.map { |word| word.reverse}.join(" ")
end
我的反向器方法:
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
所以。我来这里也是想了解一下如何做到这一点。因为语言不清楚。我去了外地,找到了足够的信息通过测试 所以,块是那些在花括号之间的东西,有时会跟随ruby中的函数,比如
list.each {|i| i.reverse}
因此,规范所做的是试图弄清楚当它这样做时会发生什么:
rerverser {"hello"}
在函数中放入yield只返回块中的任何内容,所以
def print_block
puts yield
end
print_block {"Hello world."}
#=> "Hello world"
然后你可以像操纵任何论点一样操纵收益率。街区还有很多,但是,如果你已经解决了所有的Test First's learn\u ruby练习,那么这就是解决练习所需要知道的全部内容。是的,这很重要。我共享的规范不是我做的,而是他们给我的实现方法
rerverser {"hello"}
def print_block
puts yield
end
print_block {"Hello world."}
#=> "Hello world"