Given `h = { a: 1, b: 2 }`, what does `h.fetch(:c)` do?
h = { a: 1, b: 2 }
h.fetch(:c)Read the full question →Ruby is a dynamic, deeply reflective language best known through Rails. Its metaprogramming is both the draw and the trap.
Method lookup through modules and prepend, blocks versus procs versus lambdas and their return behaviour, method_missing, mutation of frozen objects, and the singleton class.
Where it shows up: Rails product companies, internal tooling, and startups that value shipping speed.
Twenty real Ruby questions from the library, code snippet included. Nothing here is paraphrased for search engines. It is the same text a signed-in user sees.
h = { a: 1, b: 2 }
h.fetch(:c)Read the full question →class Ghost
def method_missing(name, *args)
"ghost: #{name}"
end
end
g = Ghost.new
puts g.anything # works
m = g.method(:anything) # ???Read the full question →class Roles
%i[admin editor viewer].each do |role|
define_method("#{role}?") { @role == role }
end
def initialize(r) = @role = r
end
u = Roles.new(:editor)
[u.admin?, u.editor?, u.viewer?]Read the full question →a = "pre#{ENV['X']}".freeze
b = "pre#{ENV['X']}".freeze
c = -"pre#{ENV['X']}"
d = -"pre#{ENV['X']}"
# Assume ENV['X'] is unset, so all four have equal content.Read the full question →p "ab" * 3Read the full question →class Bag
include Enumerable
def initialize(*items); @items = items; end
def each; @items.each { |i| yield i }; end
end
puts Bag.new(1, 2, 3).map.classRead the full question →p [1, nil, 2, false, 3].compactRead the full question →0.times do
puts "hi"
endRead the full question →def describe(x)
if x.nil?
"got nil"
elsif x == false
"got false"
else
"got something"
end
endRead the full question →class User
attr_accessor :name
def initialize(n)
name = n
end
end
puts "Hi, #{User.new('Sam').name}"Read the full question →name = "Sam"
puts "Hi #{name.upcase}!"Read the full question →true.class.ancestors.include?(Object)Read the full question →user = nil
user&.nameRead the full question →:foo.object_id == :foo.object_id # => true
"foo".object_id == "foo".object_id # => falseRead the full question →puts [1, 2, 3]
p [1, 2, 3]Read the full question →z = if false then 1 endRead the full question →def method_missing(name, *args)
return "dynamic" if name.to_s.start_with?("get_")
super
endRead the full question →class Vis
private
define_method(:secret) { "s" }
end
Vis.new.respond_to?(:secret) # => falseRead the full question →p(1 <=> "a")Read the full question →nums = [1, 2, 3]
doubled = nums.map { |n| n * 2 }
p numsRead the full question →We keep the correct answer, the explanation and the scoring behind sign-in so the platform stays honest, which is why the answer options and the worked explanation for every Ruby question stay behind a free account. Signing in is free and takes a few seconds.
60 distinct Ruby topics are tagged across the library. These are the real topic labels stored on the questions, not a hand-written list.
…