Issue #10064 has been updated by Marc-Andre Lafortune.


Yukihiro Matsumoto wrote:
> The original idea includes dispatch based on type (Symbol), which is not a good idea in general.

I'm not sure I understand. I think the original idea would work for other types too; the syntax would just be a shortcut for a call to `to_proc`.

For example, I'd expect the following to work too:

    x = Object.new
    def x.to_proc
      -> { true }
    end

    case 42
      when &x
        puts "Always true"
    end
    

----------------------------------------
Feature #10064: &:symbol in when clause
https://bugs.ruby-lang.org/issues/10064#change-49156

* Author: Kenta Murata
* Status: Feedback
* Priority: Normal
* Assignee: Yukihiro Matsumoto
* Category: syntax
* Target version: current: 2.2.0
----------------------------------------
Now we can put Proc objects in a when clause as this code.

~~~
require 'prime'

def test(n)
  print "#{n} is "
  case n
  when :zero?.to_proc
    puts 'zero'
  when :even?.to_proc
    puts 'an even number'
  when :prime?.to_proc
    puts 'a prime number'
  else
    puts 'a non-prime odd number'
  end
end

(1..10).each &method(:test)
~~~

I would like to write it as below:

~~~
require 'prime'

def test(n)
  print "#{n} is "
  case n
  when &:zero?
    puts 'zero'
  when &:even?
    puts 'an even number'
  when &:prime?
    puts 'a prime number'
  else
    puts 'a non-prime odd number'
  end
end

(1..10).each &method(:test)
~~~

How do you think about this new syntax, Matz?




-- 
https://bugs.ruby-lang.org/