Project

General

Profile

Actions

Feature #16372

closed

Allow pattern matching to bind instance variables

Added by jnchito (Junichi Ito) over 4 years ago. Updated over 4 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:95954]

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

Related issues 1 (0 open1 closed)

Related to Ruby master - Feature #18408: Allow pattern match to set instance variablesRejectedktsj (Kazuki Tsujimoto)Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0