Array#inquire 4

Posted by Tieg Zaharia Tue, 01 Jul 2008 17:29:00 GMT


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

Leave a response

  1. Tim Connor about 1 hour later:
    Why? What is the reason that you want the first one on a miss?
  2. Tieg about 10 hours later:
    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.
  3. Tim Connor 1 day later:
    Call it fetch_by_value and style it after fetch, for consistency:
    
    arr.fetch_by_value(value) -> throws an IndexErrror if value not found
    arr.fetch_by_value(value, default) -> default if value not found
    arr.fetch_by_value(value) { |v| block } -> calls block with value if not found
  4. Tieg 7 days later:
    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.
Comments