rubyist
rubyist

Reputation: 3132

Try method in ruby

I am trying to collect elements from an array like below

@arr.collect(&:title)

But sometimes the @arr can have some values and it throws undefined method error. So using try as below.

So how can i handle it with try method?

Upvotes: 0

Views: 887

Answers (1)

Ilya
Ilya

Reputation: 13487

You can use the way below:

@arr.collect {|e| e.respond_to?(:title) ? e.title : nil }

Or if your Ruby version > 2.3.0, safe navigation operator can be used instead of Rails try:

@arr.collect { |e| e&.title }

Upvotes: 6

Related Questions