Feature #16372
closedAllow pattern matching to bind instance variables
Description
I tried this code, but got sytax error:
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:
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):
class FooController < ApplicationController
def create
case Foo.create_foo(foo_params)
in :ok, @foo
redirect_to @foo
in :ng, _
render :new
end
end
end
Updated by shevegen (Robert A. Heiler) almost 5 years ago
If I understood you correctly then the suggestion is to allow both local and
instance variables become assignable, when before pattern matching would only
be possible to local variables, yes?
If that is the case then I think this might make sense, since we can assign
to local variables and instance variables as-is, so that would seem logical
to have pattern matching work on instance variables as well. It might be
useful to ask the ruby user who suggested pattern matching too about this,
perhaps there was a reason @variables were not considered (but it could
simply be that he did not think about it at all when suggesting the
feature).
Updated by jnchito (Junichi Ito) almost 5 years ago
shevegen (Robert A. Heiler) wrote:
If I understood you correctly then the suggestion is to allow both local and
instance variables become assignable, when before pattern matching would only
be possible to local variables, yes?
Yes, correct. And people might want to use @@variables and $variables too (I rarely use them, though) .
Updated by matz (Yukihiro Matsumoto) almost 5 years ago
- 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.
Updated by ktsj (Kazuki Tsujimoto) almost 3 years ago
- Related to Feature #18408: Allow pattern match to set instance variables added