LoginSignup
0
0

Ruby silverの模擬問題を抜粋して解説をしていきます。

下記コードを実行した出力結果を選びなさいという問題です。

class Space
  @@address = "earth"

  def self.print_address
    puts "I came from the #{@@address}"
  end
end

class Planet < Space
  def self.print_address
    puts "I live on the #{@@address}"
  end
end

Space.print_address
Planet.print_address

1.(1)I came from the earth(2)I live on the earth
2.(1)I came from the earth(2)エラーになる
3.(1)I came from the earth(2)I live on the
4.(1)I live on the earth(2)I live on the earth

まず、'Space'というクラス名を定義します。

class Space
end

次に、'@@address'というクラス変数に"earth"を初期値として定義します。

@@address = "earth"

次に、Spaceクラスの為の'self.print_address'というメソッドを定義します。
その後、'puts "I came from the #{@@address}"'で@@adressを式展開をしてコンソールに出力されます。

class Space
  @@address = "earth"

  def self.print_address
    puts "I came from the #{@@address}"
  end
end

次に、Planetというクラスを定義しSpaceクラスを継承させます。

class Planet < Space
end

次に、Planetクラスの為の'self.print_address'というメソッドを定義します。
その後、'puts "I live on the #{@@address}"'で@@adressを式展開をしてコンソールに出力されます。

class Planet < Space
  def self.print_address
    puts "I live on the #{@@address}"
  end
end

次に、Space.print_address: Spaceクラスのprint_addressメソッドを呼び出します。
Spaceクラスを使用するため、"I came from the earth"と出力されます。

Space.print_address

最後に、Planet.print_address: Planetクラスのprint_addressメソッドを呼び出します。
Planetクラスでオーバーライドされたメソッドが実行されるため、"I live on the earth"と出力されます。

Planet.print_address

解答としては1番になります。

0
0
0

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