LoginSignup
1
1

More than 5 years have passed since last update.

【翻訳】Rubyでクラスをrenameする

Last updated at Posted at 2017-11-04

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::DogWild::Dogsoundを使いたい場合、以下のようなプログラムを書くことになります。

# 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! :)

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