rubyfunctional-programming

ruby : return object if test is true


I'm looking for a function that would do the following:

def self.my_find
  object = self.first #Whatever
  return object.my_check? ? object : nil
end

Something like check:

object.check(&:my_check?)

It should exist, shouldn't it?

Here's my situation:

In a method (controller), I have some nil-able objects and I need to check something on the object to further use it.

In the event of trying to write pseudo-functional code, the logic is first to retrieve the objects, then making actions on the objects and then return those.

If I have a collection, the code would be:

result = get_my_collection_method.select(&:my_check?).map(&:my_action)

There is no issue if the select methods filters all objects, then result will equal [] but the code is still valid.

I find natural to wanting to do the same even if it is not a collection but a single object:

result = get_my_object.check(&:my_check?).try(:my_action)

But the fact that this method doesn't exist tells me there is no monadic transformation between object and array in ruby.

I guess the simplest way to achieve this is that I transform my singleton into a single value array:

result = Array(get_my_object).select(&:my_check?).map(&:my_action).first

I hope this clarifies why I was looking for such method.

But the question remains: does it exist natively? If I write it myself (even at the Object level), this is not standard, I lose the benefits of writing clean code.


Solution

  • I was looking for a similar way without creating a new variable, as the other solutions suggest. The cleanest oneliner I can come up with is:

    self.first.tap{ |obj| break unless obj.my_check? }