Reputation: 24560
I have this code:
{drop_off_lat, _ } = case student_model.drop_off_lat do
nil -> {0.0, 0}
value -> {Float.parse(value), 0}
end
{drop_off_lng, _ } = case student_model.drop_off_lng do
nil -> {0.0, 0}
value -> {Float.parse(value), 0}
end
{pick_up_lat, _ } = case student_model.pick_up_lat do
nil -> {0.0, 0}
value -> {Float.parse(value), 0}
end
{pick_up_lng, _ } = case student_model.pick_up_lng do
nil -> {0.0, 0}
value -> {Float.parse(value), 0}
end
for each key (drop_off_lat, drop_off_lng, pick_up_lat, pick_up_lng) I am checking if its nil to replace with 0, otherwise to replace with float parsing of its version.
Although its working, but I feel that the code can be more compact with fewer lines, right?
Upvotes: 0
Views: 107
Reputation: 222118
You can use for
and pattern match its return value:
map = %{
drop_off_lat: nil,
drop_off_lng: "4.5",
pick_up_lat: "6.5e2",
pick_up_lng: nil,
}
[drop_off_lat, drop_off_lng, pick_up_lat, pick_up_lng] =
for key <- [:drop_off_lat, :drop_off_lng, :pick_up_lat, :pick_up_lng] do
case map[key] do
nil -> 0.0
value -> String.to_float(value)
end
end
IO.inspect {drop_off_lat, drop_off_lng, pick_up_lat, pick_up_lng}
Output:
{0.0, 4.5, 650.0, 0.0}
Upvotes: 1