Ruby 块作为在 public_send 中展开的数组元素

Ruby block as an array element for splatting in public_send

我正在尝试使用元编程构建一个通用方法,它使用从 arraysend 操纵 methods 到使用 splat 的对象,以下是工作片段:

ALLOWED_DATA_TYPES = {
  'Integer' => [['to_i']],
  'Csv' => [['split', ',']]
}

ALLOWED_DATA_TYPES.each do |type, methods|
  define_method("#{type.downcase}_ified_value") do
    manipulated_value = value
    methods.each { |method| manipulated_value = manipulated_value.public_send(*method) }
    return manipulated_value
  end
end

到目前为止它运行良好,直到我们决定添加另一种数据类型并且它需要调用 array 上的方法,例如

"1,2,3".split(',').map(&:to_f)

现在我卡住了,因为它是一个块。从技术上讲,以下代码工作正常:

"1,2,3".public_send('split', ',').public_send(:map, &:to_f)
# => [1.0, 2.0, 3.0]

但是将 block 添加到数组会引发错误

[['split', ','], ['map', &:to_f]]
# => SyntaxError: syntax error, unexpected &, expecting ']'

我知道我可以创建一个 proc 并用 amp & 调用它,但我希望你明白它正在失去一致性,我需要一些可以与 [=19= 一起使用的东西] 使用 #define_method

定义的运算符

我现在没主意了,请帮忙。

你运气不好,& 不是运算符 - 它是一种特殊语法,只允许在函数参数(定义和调用)中使用。一种方法是为块保留数组的最后一个元素;但是你总是必须使用它(即使它只是 nil)。

methods.each { |*method, proc| manipulated_value = manipulated_value.public_send(*method, &proc) }

这应该适用于 [['split', ',', nil], ['map', :to_f]]

题外话,但请注意,可以使用 inject:

更简洁地重写这三行
manipulated_value = value
methods.each { |*method, proc| manipulated_value = manipulated_value.public_send(*method, &proc) }
return manipulated_value

变成

methods.inject(value) { |manipulated_value, (*method, proc)| manipulated_value.public_send(*method, &proc) }