Array#inquire 4
class Array
def inquire(val)
include?(val) ? val : first
end
end
Not sure if this has been done before, but it should simplify stuff this:
type = %w(sencha macha kukicha bancha).include?(params[:type]) ? params[:type] : "sencha"
into this:
type = %w(sencha macha kukicha bancha).inquire(params[:type])
Better names for this than inquire? One I thought of was Array#beg, since you don't always get what you ask for. Hm.
Comments
-
Why? What is the reason that you want the first one on a miss?
-
I know! It seems strange. I hesitated for a while, but I've actually noticed this pattern quite a few times (especially with params). Maybe I should have an optional parameter for a default value (or index) that would default to "first" if nil.
-
Call it fetch_by_value and style it after fetch, for consistency:
-
AHA! True, fetch_by_value does make more sense. Defining the default value by hand does add a little more verbosity than originally intended, but it's still better than using a ternary operator imo.