0
0
Rubyprogramming~10 mins

Why class-level behavior matters in Ruby - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a class method in Ruby.

Ruby
class Car
  def self.[1]
    "This is a class method"
  end
end
Drag options to blanks, or click blank then click option'
Ainfo
Bstart
Cdescription
Ddrive
Attempts:
3 left
💡 Hint
Common Mistakes
Using instance method names without self. prefix.
2fill in blank
medium

Complete the code to call the class method correctly.

Ruby
class Dog
  def self.[1]
    "Bark!"
  end
end

puts Dog.[1]
Drag options to blanks, or click blank then click option'
Asound
Bspeak
Cnoise
Dbark
Attempts:
3 left
💡 Hint
Common Mistakes
Calling class methods on instances instead of the class.
3fill in blank
hard

Fix the error in the code by completing the blank.

Ruby
class Cat
  def [1]
    "Meow"
  end
end

puts Cat.meow
Drag options to blanks, or click blank then click option'
Aclass.meow
Bmeow
Cself.meow
Ddef.meow
Attempts:
3 left
💡 Hint
Common Mistakes
Defining instance methods but trying to call them on the class.
4fill in blank
hard

Fill in the blank to create a class method that accesses the class variable.

Ruby
class Book
  @@count = 0

  def self.[1]
    @@count
  end
end
Drag options to blanks, or click blank then click option'
Acount
Bclass_variable
Cdef
Ddef self.count
Attempts:
3 left
💡 Hint
Common Mistakes
Using instance variables instead of class variables.
5fill in blank
hard

Fill both blanks to define a class method that increments a class variable and returns it.

Ruby
class Counter
  @@total = 0

  def self.[1]
    @@total [2] 1
  end
end
Drag options to blanks, or click blank then click option'
Aclass_variable
Bincrement
C+=
Ddef
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use self. for class methods.
Using =+ instead of +=.