virtual_monk
virtual_monk

Reputation: 120

More efficient ruby if case

I was wondering what the best way is to test a string for multiple conditions.

this = "allthisstuff"

if this.include?("a")
  # then do all this stuff
end
if this.include?("f")
  # then do all this stuff too
end
if this.include?("s")
  # also do all this stuff
end

Is there a more efficient way of doing this, or is stacking if statements the best option?

Upvotes: 1

Views: 490

Answers (1)

Richard Peck
Richard Peck

Reputation: 76784

I'd use a recursive method with callbacks.


Since you're trying to evaluate a String, you'll be best extending the String class:

#config/initializers/string.rb #-> should be in /lib 
class String
  def has? *letters
    letters.each do |letter|
      yield letter, self.include?(letter)
    end
  end
end

#app
this = "allthisstuff"
this.has?("a", "f", "s", "d") { |letter,result| puts "#{letter} #{result}" }

# -> a true
# -> f true
# -> s true
# -> d false

The above will allow you to use a single block, through which you'll be able to evaluate the passed letter:

this.has?("a", "f", "s") do |letter,result|
  if result
    case letter
      when "a"
        # do something
      when "f"
        # do something
    end
  end
end

--

If you wanted to include separate blocks (completely feasible with JS), you'd want to look at "callbacks". Although callbacks are not strictly part of the Ruby way, you may be able to do it:

#config/initializers/string.rb
class String
  def has? **letters
    letters.each do |letter,lambda|
      lambda.call(letter.to_s, self.include?(letter.to_s))
    end
  end
end

#app
this.has?({
  a: Proc.new {|letter,result| # do something },
  b: Proc.new {|letter,result| # do something else }
})

To improve this, it would be best to find the equivalent of arglist in SASS

--

Refs:

Upvotes: 1

Related Questions