2
1

Object でも Hash みたいに分割代入したい

Last updated at Posted at 2024-09-13

やりたいこと

Object でも Hash みたいに分割代入 (destructuring assignment) したい。

# Hash オブジェクトは右代入を使って分割代入ができる。
heterogeneity = { brand_and_name: 'mowl - ヘトロジェニティ', color: '紫' }
heterogeneity => { brand_and_name:, color: }
[brand_and_name, color]
#=> ["mowl - ヘトロジェニティ", "紫"]

# ちなみに Data オブジェクトでもできる。
Yoyo = Data.define(:brand_and_name, :color)
heterogeneity = Yoyo.new(brand_and_name: 'mowl - ヘトロジェニティ', color: '紫')
heterogeneity => { brand_and_name:, color: }
[brand_and_name, color]
#=> ["mowl - ヘトロジェニティ", "紫"]

# Yoyo という PORO (Plain Old Ruby Object) でも同じようなことがしたい。
class Yoyo
  # 略
end

heterogeneity = Yoyo.new(some_arguments)
heterogeneity => { brand_and_name:, color: }
[brand_and_name, color]
#=> ["mowl - ヘトロジェニティ", "紫"]

方法

class に deconstruct_keys メソッドを実装する。

class Yoyo
  attr_reader :name, :brand, :color

  def initialize(name:, brand:, color:)
    @name = name
    @brand = brand
    @color = color
  end

  def brand_and_name
    "#{@brand} - #{@name}"
  end

  def deconstruct_keys(keys)
    {
      name: @name,
      brand: @brand,
      brand_and_name: brand_and_name,
      color: @color
    }
      .slice(*keys.map(&:to_sym))
  end
end

heterogeneity = Yoyo.new(name: 'ヘトロジェニティ', brand: 'mowl', color: '紫')
heterogeneity => { brand_and_name:, color: }
[brand_and_name, color]
#=> ["mowl - ヘトロジェニティ", "紫"]

バージョン情報

$ ruby -v
ruby 3.3.4 (2024-07-09 revision be1089c8ec) [arm64-darwin23]

参考

ヘトロジェニティ

↑ コード中に出てきたヘトロジェニティはこちら 👼

2
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
2
1