0

How would you get my 'def showVars' built within the 'second' class to output the 'puts (variables)' that it inherited from the 'First' class?

class First
  @@varOne = 1 
  CONSTANT_ONE = 10 
end

class Second < First
  def showVars
    puts @@varOne
    puts CONSTANT_ONE
  end
end

My failed attempt:

class First
  @@varOne = 1 
  CONSTANT_ONE = 10 
end

class Second < First
  def showVars
    puts @@varOne
    puts CONSTANT_ONE
  end
end

puts Second.showVars # <-- fails
5
  • Define "fails". Commented Feb 25, 2018 at 18:47
  • 1
    puts Second.new.showVars Works. You have defined an instance method, not a class method. Commented Feb 25, 2018 at 18:54
  • I see Thank you. Commented Feb 25, 2018 at 18:55
  • 1
    Ruby strongly recommends naming methods and variables with only lowercase letters, that is this should be show_vars. Capital letters are reserved for ClassName and CONSTANT_NAME situations and have specific meaning in the syntax. Commented Feb 25, 2018 at 19:01
  • 1
    Good to know thanks! Commented Feb 25, 2018 at 19:04

1 Answer 1

1

You can't call Second.showVars because it's an instance method. To call it that way, you have to use a class method. You can do that by adding self in the method name.

class First
  @@varOne = 1 
  CONSTANT_ONE = 10 
end

class Second < First
  def self.showVars
    puts @@varOne
    puts CONSTANT_ONE
  end
end

puts Second.showVars

The output now is:

1
10

[Finished in 0.1s]

Class methods are equivalent to static methods in other languages.

Another point I noticed is that you named your method showVars using camelCase. Ruby methods should be named using snake_case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.