Ruby学習の一環として、週に1度Ruby関連のブログ記事(英語)を翻訳しています。
今回はクラスをrenameする方法。
原文:Renaming class in Ruby (a kinda)
↓以下本文↓
例えば犬に関するコードを変更しなければならなくなったとしましょう。犬には何種類かあって、コードは以下のようになっているとします。
module Animal
module Domestic
class Dog
def sound
"woof"
end
end
end
module Wild
class Dog
def sound
"grrr"
end
end
end
end
コードを見ると、犬には2種類あることがわかります。1つはWild
で、Animal::Wild::Dog
のようにアクセスすることができ、もう一方はDomestic
で、こちらも同様の方法でアクセスすることができます。
なので、Domestic::Dog
とWild::Dog
のsound
を使いたい場合、以下のようなプログラムを書くことになります。
# using_dog_in_animal_module.rb
require_relative "dog_in_animal_module.rb"
include Animal
puts Domestic::Dog.new.sound
puts Wild::Dog.new.sound
でも毎度Domestic::Dog.new.sound
と打つのは長くて面倒ですよね…短くすることはできるのでしょうか?幸い、Rubyではそれが可能です。以下のプログラムを見てみてください。
# renaming_class.rb
require_relative "dog_in_animal_module.rb"
DomesticDog = Animal::Domestic::Dog
WildDog = Animal::Wild::Dog
puts DomesticDog.new.sound
puts WildDog.new.sound
上記のコードの5, 6行目を見ると、クラスをrenameするようなことをしています。DomesticDog = Animal::Domestic::Dog
の箇所で Animal::Domestic::Dog
という長いクラス名をDomesticDog
という定数に置き換えており、8行目ではputs DomesticDog.new.sound
と行った短い形式で呼び出せるようになりました。
プログラムが大規模になっている場合、タイピングの工数を減らせるのはありがたいですよね。Happy coding! :)