是否有只返回一个块的值的红宝石方法? [英] Is there a ruby method that just returns the value of a block?
问题描述
我知道Object#tap
,它接受一个值并返回该值.但是,有没有一种方法可以接受一个块并返回该块求值的值?
I know about Object#tap
, which takes a value and returns that value. But is there a method that takes a block and returns the value evaluated by the block?
要在此答案中改善我的代码(比下面的代码段更复杂),我想更改
To improve my code in this answer (which is more complicated than the snippet below), I'd like to change
deck.index("A").tap {|index|
STDERR.puts "Result of indexing for #{"A".inspect} is #{index.inspect}"
}
重复"A"
的
进入
def my_method(*args)
yield *args
end
deck = ['A', 'B', 'C']
my_method("A") {|value| deck.index(value).tap {|index|
STDERR.puts "Result of indexing for #{value.inspect} is #{index.inspect}"
} }
# Result of indexing for "A" is 0
# => 0
推荐答案
所要查找的内容基本上与Lisp或OCaml中的let
等效-允许您将值临时绑定到标识符而无需引入一个新的变量进入更大的范围.在Ruby中,没有什么可以让您使用这种语法来做这种事情的.等效的Ruby将是:
What you're looking for is essentially the equivalent of let
in Lisp or OCaml — something that allows you to temporarily bind a value to an identifier without introducing a new variable into the larger scope. There isn't anything that lets you do such a thing with that syntax in Ruby. The equivalent Ruby would be:
lambda {|value| deck.index(value).tap {|index|
STDERR.puts "Result of indexing for #{value.inspect} is #{index.inspect}"
} }.call 'A'
您当然可以只写一个像这样的方法:
You could of course just write a method like:
def let(*values)
yield *values
end
这篇关于是否有只返回一个块的值的红宝石方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!