2013-12-11 23 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的书,很容易失去在任何给定点发生的事情的轨道。

当我看到上面的答案,质疑你的问题,我的第一个反应方式,“这是一个公平的问题,他们采取一个整数,并把它当作一个布尔。”

在某个时候,我错过了我们停止推动整数并开始移动布尔的地方。

底线,正在使用三元运算符,因为它在情况下是有意义的。