您好,我的问题是使用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