我正在尝试理解Mastermind游戏中使用的方法,但我不理解yield块产生的内容;也不理解实际方法的返回...
代码如下:
#lib/mastermind/gameboard.rb
require 'colorize'
def colorize(set, is_color_code)
colors = []
text = is_color_code ? "0" : "."
set.colors.each { |color| colors.push(text.public_send(color.to_sym)) }
colors.join(' ')
end我的主要问题是:如果#colors返回一个散列中所有键的数组,而我只是简单地将本地text变量推送到本地colors数组,并与#public_send(color.to_sym)连接,那么#colorize方法在这里返回的不是一个"0".color或".".color的数组吗?
我认为需要说明的是,#colorize是Colorize Gem中的一个方法,然而,这个#colorize方法是project I'm reviewing.中一个单独类的一部分
发布于 2019-09-23 03:16:43
让我们逐行分解这个方法,看看是怎么回事。
def colorize(set, is_color_code)
colors = [] # instantiate an array
text = is_color_code ? "0" : "." # ternary assignment if is_color_code == true || false
# set.colors is an array of strings like ['white', 'white', 'white', 'white']
# set.colors.each { |color| colors.push(text.public_send(color.to_sym)) }
# line above this refactored to comment
set.colors.each do |color|
# color.to_sym # convert the string to symbol so 'white' becomes :white
# you must pass a symbol to public_send
# so this is sending the name of the color to the string as provided by the gem.
colors.push( text.public_send(color.to_sym) ) # push the return of that into array
end
# In Ruby the method always returns whatever the output of the last line returns.
colors.join(' ') # returns the colors array a string joined by spaces
end在本例中,colorize方法在GameBoard类中定义。因此,当在GameBoard的实例上调用该方法时,它的行为将与定义的一样。其中,as 'blue'.colorize(:blue) here .colorize方法扩展String类以响应传递的颜色符号的颜色代码
示例
'blue'.colorize(:blue) # same as 'blue'.blue
=>"\e[0;34;49mblue\e[0m"重构版本
def colorize(set, is_color_code)
text = is_color_code ? "0" : "."
set.colors
.map { |color| text.public_send(color.to_sym) }
.join(' ')
endhttps://stackoverflow.com/questions/58052030
复制相似问题