Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array fetch or default function

Tags:

arrays

ruby

I need the following logic. If array contains value, return it else return some default value. So far, I've found this can be achieved by using delete:

array.delete(value) || default_value

But, obviously, it modifies the array. Is there a similar function like fetch with default which takes an element instead of an index?

PS. I know this can be rewritten as array.include?(value) ? value : default_value, the question is just for the sake of cleaner code.

like image 809
RocketR Avatar asked Dec 30 '25 01:12

RocketR


1 Answers

Update: There's one way I can think of, but that's harder to read than the ternary:

 (array & [value]).first || default_value

You could monkey-patch that into Array if you are so inclined:

class Array
  def fetch_value(value, default)
    (self & [value]).first || default
  end
end

a = *1..3
a.fetch_value(4, "foo")
#=> "foo"

Old answer, before I realized you want to use the value for the lookup, not the index:

Array#fetch takes an optional second argument:

array.fetch(index, default)

Here's an example:

a = *1..3
a.fetch(4, "foo")
#=> "foo"
like image 145
Michael Kohl Avatar answered Dec 31 '25 18:12

Michael Kohl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!