Kit Ho
Kit Ho

Reputation: 26968

Ruby CSV how to return nil instead of undefined method error?

 csv_content = CSV.generate do |csv|
      csv << [
        "Bus number",
        "Bus name",
        "Bus Driver Name",
      ]

      @buses.each do |bus|
        csv << [
          bus.number,
          bus.name,
          bus.driver.name
        ]
        end
    end

Here is a code snippet to generate csv content, however, bus.driver.name will throw nil class error if bus.driver is nil. How can i return nil instead? How can we do it more elegant?

Upvotes: 2

Views: 547

Answers (1)

Alex D
Alex D

Reputation: 30445

If you are using Rails (or Active Support):

bus.driver.try(:name)

If not, just add it yourself:

class Object
  alias :try :send
end
class NilClass
  def try(method); end
end

Upvotes: 3

Related Questions