我正在创建一个包含 lambdas 作为 Ruby 值的哈希。我想访问 lambda 中的键名。
哈希是匿名函数 (lambdas) 的集合,它们接受输入并执行特定任务。所以,我正在制作一个绘制形状的散列,因此散列中的键是形状名称,如圆形、方形,而这个键的值是一个 lambda,它接受输入并执行一些任务,从而绘制出形状. 所以,在这里我想在 lambda 中打印形状的名称,即键。
真实的例子:
MARKER_TYPES = {
# Default type is circle
# Stroke width is set to 1
nil: ->(draw, x, y, fill_color, border_color, size) {
draw.stroke Rubyplot::Color::COLOR_INDEX[border_color]
draw.fill Rubyplot::Color::COLOR_INDEX[fill_color]
draw.circle(x,y, x + size,y)
},
circle: ->(draw, x, y, fill_color, border_color, size) {
draw.stroke Rubyplot::Color::COLOR_INDEX[border_color]
draw.fill Rubyplot::Color::COLOR_INDEX[fill_color]
draw.circle(x,y, x + size,y)
},
plus: ->(draw, x, y, fill_color, border_color, size) {
# size is length of one line
draw.stroke Rubyplot::Color::COLOR_INDEX[fill_color]
draw.line(x - size/2, y, x + size/2, y)
draw.line(x, y - size/2, x, y + size/2)
},
dot: ->(draw, x, y, fill_color, border_color, size) {
# Dot is a circle of size 5 pixels
# size is kept 5 to make it visible, ideally it should be 1
# which is the smallest displayable size
draw.fill Rubyplot::Color::COLOR_INDEX[fill_color]
draw.circle(x,y, x + 5,y)
},
asterisk: ->(draw, x, y, fill_color, border_color, size) {
# Looks like a five sided star
raise NotImplementedError, "marker #{self} has not yet been implemented"
}
}
哈希包含大约 40 个这样的键值对。
期望的输出是marker star has not yet been implemented
一个简单的例子:
HASH = {
key1: ->(x) {
puts('Number of key1 = ' + x.to_s)
}
}
而不是硬编码,key1
我想在值中获取键的名称,它是一个 lambda,因为哈希中有很多 lambda。
替换key1
为#{self}
打印类而不是键名。