LoginSignup
0
0

More than 1 year has passed since last update.

はじめに

移植やってます。
( from python 3.7 to ruby 2.7 )

Dict (Python)

辞書の四則演算が必要らしいのですが、辞書を継承してメソッドを追加しているみたいです。

Hash (Ruby)

class H < Hash
  def initialize
    self.default = 0
  end
  def +(other)
    case other
    when Hash
      other.each do |k, v|
        self[k] += v
      end
    when Integer || Float
      self.each do |k, _|
        self[k] += other
      end
    end
  end
  def *(other)
    case other
    when Hash
      other.each do |k, v|
        self[k] *= v
      end
    when Integer || Float
      self.each do |k, _|
        self[k] *= other
      end
    end
  end
end

h = H.new
h + {'A' => 1}
h + {'A' => 1, 'B' => 1}
p h # {"A"=>2, "B"=>1}
h + 3
p h # {"A"=>5, "B"=>4}
h * {'B' => 2, 'C' => 2}
p h # {"A"=>5, "B"=>8, "C"=>0} 
h * 2
p h # {"A"=>10, "B"=>16, "C"=>0}

そられしくなりました。
本来であれば交換則で、例えば、Integer * Hashも必要なのですが。
もしかしたら、gemsnumpy/scipyにあるかもしれませんね。

メモ

  • Python の 辞書 の四則演算 を学習した
  • 百里を行く者は九十里を半ばとす
0
0
2

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
0
0