Following up on my previous post (where I showed how to set default values in Ruby methods), it turns out you can write not just a single expression on the right side, but an entire block of code inside a begin-end construct. Of course, I’m not sure if you should use this in production, as it might cause some unpredictable side effects. Still, this is valid Ruby syntax. And if you want to become a experienced developer, knowing these nuances is definitely worth it.
class MyClass
def initialize(arg = nil)
@arg = arg
end
def perform(
arg:
begin
if @arg.nil?
(1..100).sum { it.odd? ? it : 0 }
else
@arg
end
end
)
puts "arg: #{arg.inspect}"
end
end
MyClass.new(100).perform # arg: 100
MyClass.new.perform # arg: 2500
MyClass.new.perform(arg: 77) # arg: 77