[ruby-core:95984] [Ruby master Feature#16372] Allow pattern matching to bind instance variables

[email protected]
Newsgroups gmane.comp.lang.ruby.core
Message-ID <redmine.journal-82817.20191127140207.e8c9a741a5a516ca@ruby-lang.org>
Issue #16372 has been updated by matz (Yukihiro Matsumoto).

Status changed from Open to Rejected

Extending pattern variables to non-local variables would make pattern-matching more complex and confusing. I reject the idea (at least for now). There might be a chance to make pinned variables (`^a`) to pinned expression in the future.

Matz.


----------------------------------------
Feature #16372: Allow pattern matching to bind instance variables
https://bugs.ruby-lang.org/issues/16372#change-82817

* Author: jnchito (Junichi Ito)
* Status: Rejected
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
I tried this code, but got sytax error:

```ruby
case [1, 2]
in @a, @b
end
```

```
syntax error, unexpected instance variable, expecting '}'
    in @a, @b
       ^~
```

I think it would be more useful if we could bind instance variables with pattern matching.

## Use case

I understand this is not Rails way, but we have some codes like this:

```ruby
def Foo.create_foo(params)
  if valid?(params)
    [:ok, create(params)]
  else
    [:ng, nil]
  end
end

class FooController < ApplicationController
  def create
    result, @foo = Foo.create_foo(foo_params)

    case result
    when :ok
      redirect_to @foo
    when :ng
      # @foo will be used in view
      render :new
    else
      raise "Unknown result: #{result}"
    end
  end
end
```

I thought I could make it simpler with pattern matching (but impossible):

```ruby
class FooController < ApplicationController
  def create
    case Foo.create_foo(foo_params)
    in :ok, @foo
      redirect_to @foo
    in :ng, _
      render :new
    end
  end
end
```





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

Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.