3 ms·
Ruby already had a sort of limited form of rightward assignment, in exception rescue: begin #... do something rescue StandardError => ex #.
by inopinatus 6y ago
Ruby already had a sort of limited form of rightward assignment, in exception rescue:
begin
#... do something
rescue StandardError => ex
#... handle exception
end
The ex here can be any assignment expression, it's not just a lexical variable. So you could already do this:
class Guru
def meditate=(exception)
puts "caught #{exception.inspect}"
end
end
# later ...
rescue OutOfCheeseError => Guru.new.meditate
i.e. creating a nice opportunity for passing error handlers around as an argument; or, this worrying idea:
rescue TransactionError => Thread.current[:exception]
and now I'm afraid you can do this:
Cat = Struct.new(:name) do
class << self
def all() = @all ||= Set.new
def adopt=(...)
all << new(...)
end
end
end
"Astrid" => Cat.adopt
- rco8786 6y agoOh the error handler example is kinda cool, especially paired with inline rescues def my_method .. code .. rescue FileNotFoundError => FileNotFoundHandler rescue StandardError => StandardErrorHandler end But yea, as is so often the case with ruby, you can really shoot yourself if you try hard enough :P