Stefan Hagen
Stefan Hagen

Reputation: 658

Rails: if statement in .map()

I want to map some values from a table to an array. Works fine, except for the fact that the database has some nil values in it, which creates invalid JSON. So far I have this:

@markers = ExtendedProfile.all.map{|u|[u.city, u.latitude, u.longitude]}

Now what I want to do is check if the fields are filled in, and if not, enter a default value. So for example if u.latitude == nil I want to enter 0.0 in the array, instead of nil. Any idea about how to accomplish this?

Upvotes: 2

Views: 5835

Answers (2)

MurifoX
MurifoX

Reputation: 15089

For better understanding, you can extend to the map block syntax like this:

@markers = ExtendedProfile.all.map do |u|
  if u.latitude.nil?
    [0, 0]
  else
    [u.city, u.latitude, u.longitude]
  end
end

Upvotes: 2

user740584
user740584

Reputation:

Use u.latitude || 0.0:

@markers = ExtendedProfile.all.map{|u|[u.city, u.latitude || 0.0, u.longitude || 0.0]}

Upvotes: 1

Related Questions