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
  • 226,338
  • 43
  • 373
  • 367

5 Answers5

17

Not in ruby but in ActiveSupport:

characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
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,657
  • 5
  • 63
  • 75
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
  • 27,320
  • 6
  • 84
  • 112
1

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

"Hello.".end_with?(',', '.') #=> true
steenslag
  • 79,051
  • 16
  • 138
  • 171
  • 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
  • 165,429
  • 45
  • 277
  • 381