ruby - 如何获取值中的键名以在 Ruby 哈希中打印
问题描述
我正在创建一个包含 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}
打印类而不是键名。
解决方案
我不认为这是可以做到的。哈希是键和值的集合。键是唯一的,值不是。您正在询问一个值(在这种情况下是一个 lambda,但它并不重要)它属于哪个键。我可以是一个,没有一个或多个;没有办法让价值“知道”。询问哈希值,而不是值。
推荐阅读
- javascript - 任何人都可以在下面的示例中解释它的用法吗?
- sitecore - Sitecore 8 - 清除所有用户的自定义配置文件字段
- mysql - SQL:显示缺失数据的最简单方法
- html - 如何将 div 放置在窗口/导航栏 HTML 的底部 - materializecss
- android - Cordova Crosswalk 插件不起作用(`cordova-plugin-crosswalk-webview`)
- git - git:无法锁定配置文件权限被拒绝和无效参数
- java - 使用带有 API 密钥的 Artifactory Java 客户端?
- sql - 在存储过程中使用插入语句从一个表中复制一些信息并从 VBA 插入新信息
- scala - 为什么我的初始化对象没有被传递给我的 spark 任务
- html - 带有粘性标题的表。与表格相比,标题中的最后一列太宽