首页 > 解决方案 > 如何获取值中的键名以在 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}打印类而不是键名。

标签: rubylambdaruby-hash

解决方案


我不认为这是可以做到的。哈希是键和值的集合。键是唯一的,值不是。您正在询问一个值(在这种情况下是一个 lambda,但它并不重要)它属于哪个键。我可以是一个,没有一个或多个;没有办法让价值“知道”。询问哈希值,而不是值。


推荐阅读