Project

General

Profile

Actions

Feature #11737

closed

Pass in expression to then block in `case expression`

Added by danielpclark (Daniel P. Clark) over 6 years ago. Updated over 6 years ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:71664]

Description

Ruby's case <expression> scenario allows the expression to be tested in the when test with :===, but in the then block the expression is not accessible. Only if the expression has been assigned to a variable beforehand can it be checked.

case 4
when ->i{ puts :when; true}
  ->i{ puts i}
else
  :foo
end
# when
#  => #<Proc:0x00000000d91e58@(irb):16 (lambda)> 

case 4
when ->i{ puts :when; true}
  puts _
else
  :foo
end
# when
# #<Proc:0x00000000d91e58@(irb):16 (lambda)>
#  => nil 

case 4
when 4
then _
end
#  => nil

case 4
when 4
then ->i{puts i}
end
#  => #<Proc:0x000000015f9be0@(irb):36 (lambda)> 

If some one wanted to give an expression after case that wasn't assigned to a variable then there is no access to it in the then block.

I suggest assigning the expression to the _ variable during a case/when/then scenario. Here's a rather contrived example use case.

case Enumerator.new do |y| y << 1; y << 2; y << 3; end
when ->e{ 2.times e.next; true}
then _.peek
end == 3
Actions

Also available in: Atom PDF