LoginSignup
0
1

More than 1 year has passed since last update.

[py2rb] 自作ライブラリの関数の呼び出し

Last updated at Posted at 2022-02-03

はじめに

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

関数 (Python)

bb.py
def make_qv(x):
    return x + 1

qv = make_qv(1)
main.py
import bb

print(bb.make_qv(2))
print(bb.qv)
output
3
2

def make_qvmainbbの双方から呼び出し可能です。

どうすRuby

bb.rb
module BB
  def make_qv(x)
    return x + 1
  end

  qv = make_qv(1)
end
main.rb
require_relative 'BB'

puts BB.make_qv(2)
puts BB.qv
output
undefined method `make_qv' for BB:Module

おお、qv = make_qv(1)でメソッドが見つからないと仰せですか。
ここは、モジュールの特異メソッドで。

bb.rb
module BB
  def self.make_qv(x)
    return x + 1
  end

  qv = make_qv(1)
end
output
3
undefined method `qv' for BB:Module

ああ、ゲッターが無いのか。

bb.rb
module BB
  def self.make_qv(x)
    return x + 1
  end

  def self.qv
    @qv ||= make_qv(1)
  end
end
output
3
2

よしよし。

今回の例では、module_function :make_qv, :qvでもいけますが、module BB内で@qvを利用する場合は特異メソッドでないと、動作しないようです。

メモ

  • Python の 関数の呼び出し を学習した
  • 百里を行く者は九十里を半ばとす
0
1
4

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
1