Is there a ruby method that just returns the value of a block?

后端 未结 2 1882
借酒劲吻你
借酒劲吻你 2020-12-20 09:37

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?

2条回答
  •  孤城傲影
    2020-12-20 10:04

    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
    

提交回复
热议问题