0
0

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.

Python to RubyAdvent Calendar 2021

Day 13

[py2rb] 辞書の値が関数

Last updated at Posted at 2022-01-19

はじめに

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

辞書の値が関数 (Python)

def a(k, v):
    print(k, v)

def b(k, v):
    print(k, v)

h = {'func a': a, 'func b': b}

h['func a']('A', 1)
h['func b']('B', 2)

# A 1
# B 2

辞書の値に関数を入れておいて、引数を渡します。
動的プログラミングですねえ。

失敗 (Ruby)

def a(k, v)
  p [k, v]
end

h = {'func a' => a}

main.rb:1:in `a': wrong number of arguments (given 0, expected 2) (ArgumentError)

ハッシュにメソッドを入れた時点でエラーになります。

成功 lambda (Ruby)

a = lambda { |k, v| p [k, v] }
b = lambda { |k, v| p [k, v] }

h = {'func a' => a, 'func b' => b}

h['func a'].call('A', 1)
h['func b'].call('B', 2)

# ["A", 1]
# ["B", 2]

lambdaだと成功します。

成功 method (Ruby)

def a(k, v)
  p [k, v]
end

def b(k, v)
  p [k, v]
end

h = {'func a' => 'a', 'func b' => 'b'}

method(h['func a']).call('A', 1)
method(h['func b']).call('B', 2)

# ["A", 1]
# ["B", 2]

defのままで行いたい場合は、methodを使用します。

成功 class (Ruby)

class A
  def self.call(k, v)
    p [k, v]
  end
end

module B
  def self.call(k, v)
    p [k, v]
  end
end

h = {'func a' => A, 'func b' => B}

h['func a'].call('A', 1)
h['func b'].call('B', 2)

# ["A", 1]
# ["B", 2]

classmoduleもいけてる。

メモ

  • 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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?