1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

#Ruby で to_hash メソッドのある Class のインスタンスを、キーワード引数を可変で受け取るメソッドに渡すと、ハッシュに変換されてしまう

Last updated at Posted at 2020-05-02
# Ruby 2.7

# to_hash method not implemented class
class ToHashNotImplementedUser
  def initialize(name:, age:)
    @name = name
    @age = age
  end
end

# to_hash method implemented class
class ToHashImplementedUser
  def initialize(name:, age:)
    @name = name
    @age = age
  end

  def to_hash
    {
      name: @name,
      age: @age
    }
  end
end

def show_args(*args, **keyword_args)
  puts "args: #{args}"
  puts "keyword_args: #{keyword_args}"
end


# ---------------------------
# ToHashNotImplementedUser Case
# ---------------------------

to_hash_not_implemented_bob = ToHashNotImplementedUser.new(name: "Bob", age: 30)

show_args(to_hash_not_implemented_bob)
# Receives as *args
#
#   args: [#<ToHashNotImplementedUser:0x00007fe7f708b038 @name="Bob", @age=30>]
#   keyword_args: {}


# ---------------------------
# ToHashImplementedUser Case
# ---------------------------

to_hash_implemented_alice = ToHashImplementedUser.new(name: "Alice", age: 20)

show_args(to_hash_implemented_alice)
# Receives as *keyword_args
#
# warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
#
# args: []
# keyword_args: {:name=>"Alice", :age=>20}

show_args(**to_hash_implemented_alice)
# Receives as *keyword_args
#
# No Warning
#
#   keyword_args: {:name=>"Alice", :age=>20}
#   args: []

show_args(to_hash_implemented_alice, **{})
# Receives as *args
#
# Explicity pass empty keyword args
#
#   args: [#<ToHashImplementedUser:0x00007fcf8d823db8 @name="Alice", @age=20>]
#   keyword_args: {}

問題

  • to_hash メソッドがある class のインスタンスを、可変長のキーワード引数 ( **keyword_args )を受け取るメソッドに渡すと、インスタンスではなくてハッシュになってしまう
  • Ruby2.7 までのハッシュからキーワード引数への自動変換の副作用的なものだと思う

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?