Reason #175 •
June 24th, 2026
Conditional method definitions
In Ruby, we can define methods conditionally based on runtime conditions. This is useful for things like:
Ruby
class MyClass
# Define methods based on Ruby version
if RUBY_VERSION >= "3.0"
def my_method
puts "Running on Ruby 3.0 or later"
end
else
def my_method
puts "Running on an older version of Ruby"
end
end
# Define methods based on the presence of a gem
if defined?(SomeGem)
def another_method
puts "SomeGem is defined"
end
else
def another_method
puts "SomeGem is not defined"
end
end
# Define methods based on environment variables
if ENV["MY_ENV_VAR"] == "true"
def env_method
puts "Environment variable is set to true"
end
else
def env_method
puts "Environment variable is not set to true"
end
end
end
We could of course also do these checks inside of the methods, but defining them conditionally is more efficient, as it avoids unnecessary checks on every method call.
This touches on one of the most magical things about Ruby to me - that it's just Ruby all the way down, whether we're inside a class definition or inside a method. No special syntax or template language required
History
Conditional method definitions have been possible since Ruby's inception, because if, class, module, and def have always belonged to the same executable language rather than to a separate declaration system.