如何获取传递到块中的参数的名称?
How to get the name of the arguments passed into a block?
在Ruby中,您可以这样做:
prc = lambda{|x, y=42, *other|}
prc.parameters #=> [[:req, :x], [:opt, :y], [:rest, :other]]
特别是,我感兴趣的是能够在上面的示例中获取 x
和 y
的参数名称。
在Crystal中,我有以下情况:
def my_method(&block)
# I would like the name of the arguments of the block here
end
在 Crystal 中如何做到这一点?
虽然这在 Ruby 中已经听起来很奇怪,但在 Crystal 中无法做到这一点,因为在您的示例中该块已经没有参数。另一个问题是这些信息在编译后已经丢失了。所以我们需要在编译时访问它。但是您不能在编译时访问运行时方法参数。但是,您可以使用宏访问该块,然后甚至可以在不显式提供的情况下允许对该块进行任意签名:
macro foo(&block)
{{ block.args.first.stringify }}
end
p foo {|x| 0 } # => "x"
为了扩展 Jonne Haß 的精彩回答,Ruby parameters
方法的等价物如下所示:
macro block_args(&block)
{{ block.args.map &.symbolize }}
end
p block_args {|x, y, *other| } # => [:x, :y, :other]
请注意,块参数在 Crystal 中始终是必需的,并且不能有默认值。
在Ruby中,您可以这样做:
prc = lambda{|x, y=42, *other|}
prc.parameters #=> [[:req, :x], [:opt, :y], [:rest, :other]]
特别是,我感兴趣的是能够在上面的示例中获取 x
和 y
的参数名称。
在Crystal中,我有以下情况:
def my_method(&block)
# I would like the name of the arguments of the block here
end
在 Crystal 中如何做到这一点?
虽然这在 Ruby 中已经听起来很奇怪,但在 Crystal 中无法做到这一点,因为在您的示例中该块已经没有参数。另一个问题是这些信息在编译后已经丢失了。所以我们需要在编译时访问它。但是您不能在编译时访问运行时方法参数。但是,您可以使用宏访问该块,然后甚至可以在不显式提供的情况下允许对该块进行任意签名:
macro foo(&block)
{{ block.args.first.stringify }}
end
p foo {|x| 0 } # => "x"
为了扩展 Jonne Haß 的精彩回答,Ruby parameters
方法的等价物如下所示:
macro block_args(&block)
{{ block.args.map &.symbolize }}
end
p block_args {|x, y, *other| } # => [:x, :y, :other]
请注意,块参数在 Crystal 中始终是必需的,并且不能有默认值。