Skip to content

Instantly share code, notes, and snippets.

@domhnall
Last active November 20, 2022 21:36
Show Gist options
  • Save domhnall/5ba8673b8ecae9b75030f7988e444e26 to your computer and use it in GitHub Desktop.
Save domhnall/5ba8673b8ecae9b75030f7988e444e26 to your computer and use it in GitHub Desktop.
Short quiz to test how well you know the ruby object model. See the [blog post](https://www.vector-logic.com/blog/posts/test-yourself-on-ruby-object-model) to have a go at the quiz
# To test yourself on the actual quiz, see
# https://www.vector-logic.com/blog/posts/test-yourself-on-ruby-object-model
puts "Question 1"
class First; end
f = First.new
puts f.class.superclass # Object
puts "\n\n"
puts "Question 2"
puts Class.ancestors # [ Class, Module, Object, Kernel, BasicObject ]
puts "\n\n"
puts "Question 3"
class Developer < Array; end
d = Developer.new
puts d.singleton_class.superclass # Developer
puts "\n\n"
puts "Question 4"
module A; end
module B; end
class Foo
include A
include B
end
puts Foo.new.class.ancestors[1] # Returns B
puts "\n\n"
puts "Question 5"
class Bar; end
puts Bar.ancestors.map(&:class) # [Class, Class, Module, Class]
puts "\n\n"
puts "Question 6"
puts BasicObject.instance_methods & [:object_id, :equal?, :inspect, :instance_of, :!=] # [ :equal?, :!= ]
puts "\n\n"
puts "Question 7"
class Baz; end
baz = Baz.new
puts baz.singleton_class.ancestors.size # Outputs 5
puts "\n\n"
puts "Question 8"
class Qux; end
Qux.class_eval{ def work; end }
puts Qux.instance_methods(false) # Outputs [:work]
puts "\n\n"
puts "Question 9"
module Italian
def speak
"#{super} 🤌"
end
end
module Boxer
def speak
"Grrr, #{super}"
end
end
class Rocky
prepend Italian
include Boxer
def speak
"Yo Adrian"
end
end
puts Rocky.new.speak
puts Rocky.ancestors
puts "\n\n"
puts "Question 10"
class User
def breathe; end
end
u = User.new
def u.dance; end
puts u.class.instance_methods(false).include?(:breathe) # true
puts u.class.instance_methods(false).include?(:dance) # false
puts u.singleton_class.instance_methods(false).include?(:dance) # true
puts u.singleton_class.instance_methods(false).include?(:breathe) # false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment