Ruby 调用一个参数时,从一个用#each迭代的Gem调用一个与方法链接的参数,yield块的返回是什么?
我试图理解一种在智囊团游戏中使用的方法,但我不理解产量块在产生什么;或者返回实际的方法 代码如下:Ruby 调用一个参数时,从一个用#each迭代的Gem调用一个与方法链接的参数,yield块的返回是什么?,ruby,methods,rubygems,yield,Ruby,Methods,Rubygems,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_sy
#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”或“.”的数组吗.颜色
我认为需要说明的是,
#colorize
是colorize Gem中的一个方法,但是,这个#colorize
方法是中一个单独类的一部分,让我们逐行分解该方法,看看发生了什么
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)
此处。colorize
方法扩展字符串
类以响应传递的颜色符号的颜色代码
范例
'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(' ')
end
澄清set.colors的数组对象:如果
set
在调用#colorize
之前是一个字符串数组,那么调用#colorize
时#colorize
方法做了什么?你在那里得到了一些关于public\u send
的错误信息。该方法没有从Ruby中删除,在最新的2.6.4版本中仍然存在。不同之处在于,只调用公共方法,同时也可以调用私有或受保护的方法。set.colors
是一个实例变量,分配给Hint
或ColorCode
的实例,它们是作为第一个参数传递给colorize
方法的对象。请参阅和中定义的初始化方法。因此您正确地认为set.colors
与colorize gem无关。由于Ruby的duck类型特性,您无法知道set
参数是什么。如果您想知道set
的内容是什么,您可以在colorize
方法中添加一些调试,或者只需查看。如果有疑问,请尝试查找调用该方法的位置,如@3limin4t0r在前面的注释中所述。很高兴它现在有意义了。