10

I often find myself checking if some value belongs to some set. As I understand, people normally use Enumerable#member? for this.

end_index = ['.', ','].member?(word[-1]) ? -3 : -2

However, this feels a little less elegant than most of things in Ruby. I'd rather write this code as

end_index = word[-1].is_in?('.', ',') ? -3 : -2

but I fail to find such method. Does it even exist? If not, any ideas as to why?

Sergio Tulentsev
  • 219,187
  • 42
  • 361
  • 354

5 Answers5

17

Not in ruby but in ActiveSupport:

characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true
Joachim Sauer
  • 291,719
  • 55
  • 540
  • 600
Vasiliy Ermolovich
  • 24,067
  • 5
  • 78
  • 76
10

You can easily define it along this line:

class Object
  def is_in? set
    set.include? self
  end
end

and then use as

8.is_in? [0, 9, 15]   # false
8.is_in? [0, 8, 15]   # true

or define

class Object
  def is_in? *set
    set.include? self
  end
end

and use as

8.is_in?(0, 9, 15)   # false
8.is_in?(0, 8, 15)   # true
undur_gongor
  • 15,304
  • 4
  • 59
  • 73
1

Not the answer for your question, but perhaps a solution for your problem.

word is a String, isn't it?

You may check with a regex:

end_index = word =~ /\A[\.,]/  ? -3 : -2

or

end_index = word.match(/\A[\.,]/)  ? -3 : -2
knut
  • 26,435
  • 6
  • 84
  • 110
1

In your specific case there's end_with?, which takes multiple arguments.

"Hello.".end_with?(',', '.') #=> true
steenslag
  • 76,334
  • 16
  • 131
  • 165
  • The question was about general case, I just pasted the latest occurence in code. But thanks for the tip, I didn't know about this method. – Sergio Tulentsev Nov 16 '11 at 01:45
0

Unless you are dealing with elements that have special meaning for === like modules, regexes, etc., you can do pretty much well with case.

end_index = case word[-1]; when '.', ','; -3 else -2 end
sawa
  • 160,959
  • 41
  • 265
  • 366