2013-12-11 29 views
0

您好,我的問題是使用RSpec book中使用的注入方法與codebreaker遊戲。我無法閱讀和理解它在做什麼。我已閱讀過該方法的解釋; http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-inject,但目前尚不清楚。有人可以指導一個新手嗎?注入方法在Rspec書中使用,上下文:Codebreaker遊戲

1).inject後的0的參數是什麼意思?在範圍內0..3的第一個索引點?
2)我看到count是累加器備註值,該索引是索引點,但塊如何被利用並綁定到下一行代碼中?

3)爲什麼使用三元運算符?

片段放在問題的代碼組成:

def exact_match_count(guess) 
    (0..3).inject(0) do |count, index| 
    count + (exact_match?(guess, index) ? 1 : 0) 
    en 
end 

def number_match_count(guess) 
    (0..3).inject(0) do |count, index| 
    count + (number_match?(guess, index) ? 1 : 0) 
    end 
end 

我相信它是平行與這個例子中卻看不到它。

# find the longest word 
longest = %w{ cat sheep bear }.inject do |memo, word| 
    memo.length > word.length ? memo : word 
end 

longest          #=> "sheep" 

完整的代碼更大的背景:

module Codebreaker 
    class Game 

def initialize(output) 
    @output = output 
end 

def start(secret) 
    @secret = secret 
    @output.puts 'Welcome to Codebreaker!' 
    @output.puts 'Enter guess:' 
end 

def guess(guess) 
    @output.puts '+' *exact_match_count(guess) + '-'*number_match_count(guess) 
end 

def exact_match?(guess, index) 
    guess[index] == @secret[index] 
end 

def number_match?(guess, index) 
    @secret.include?(guess[index]) && !exact_match?(guess, index) 
end 

def exact_match_count(guess) 
    (0..3).inject(0) do |count, index| 
    count + (exact_match?(guess, index) ? 1 : 0) 
    end 
end 

def number_match_count(guess) 
    (0..3).inject(0) do |count, index| 
    count + (number_match?(guess, index) ? 1 : 0) 
    end 
end 

    end 
end 

回答

1

1)什麼的.inject後傳遞0的說法是什麼意思? 範圍內0..3的第一個索引點?

0是初始累加器值。如果不存在,範圍的第一個元素將作爲累加器值傳遞,第二個元素作爲索引傳遞,繞過將塊邏輯應用到第一個索引。

2)I看到計數累加器備忘錄值和索引是 索引點,但是如何被使用的嵌段和紮成代碼 下一行?

該塊將針對該範圍中的每個元素執行。我不知道你的意思是「下一行」。塊中只有一條語句,方法在塊之後立即終止。

3)爲什麼使用三元運算符?

不確定你在問「爲什麼」。它完成了預期的邏輯。

0

3)爲什麼使用三元運算符?

如果您一直在駕駛RSpec的書,很容易失去在任何給定點發生的事情的軌道。

當我看到上面的答案,質疑你的問題,我的第一個反應方式,「這是一個公平的問題,他們採取一個整數,並把它當作一個布爾。」

在某個時候,我錯過了我們停止推動整數並開始移動布爾的地方。

底線,正在使用三元運算符,因爲它在情況下是有意義的。