Why is it bad style to `rescue Exception => e` in Ruby?

TL;DR: Use StandardError instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing Exception is probably okay. Exception is the root of Ruby’s exception hierarchy, so when you rescue Exception you rescue from everything, including subclasses such as SyntaxError, LoadError, and Interrupt. Rescuing Interrupt prevents … Read more

What is attr_accessor in Ruby?

Let’s say you have a class Person. class Person end person = Person.new person.name # => no method error Obviously we never defined method name. Let’s do that. class Person def name @name # simply returning an instance variable @name end end person = Person.new person.name # => nil person.name = “Dennis” # => no … Read more

Strange, unexpected behavior (disappearing/changing values) when using Hash default value, e.g. Hash.new([])

First, note that this behavior applies to any default value that is subsequently mutated (e.g. hashes and strings), not just arrays. It also applies similarly to the populated elements in Array.new(3) { [] }. TL;DR: Use Hash.new { |h, k| h[k] = [] } if you want the most idiomatic solution and don’t care why. … Read more

What does map(&:name) mean in Ruby?

It’s shorthand for tags.map(&:name.to_proc).join(‘ ‘) If foo is an object with a to_proc method, then you can pass it to a method as &foo, which will call foo.to_proc and use that as the method’s block. The Symbol#to_proc method was originally added by ActiveSupport but has been integrated into Ruby 1.8.7. This is its implementation: class … Read more

tech