![]() Ruby has eleven methods to find elements in an array. ![]() ![]() Raise "Not allowed" unless ALLOWED_METHODS.include?(what.to_sym)Ī quick test reveals that calling include? on a 10 element Set is about 3.5x faster than calling it on the equivalent Array (if the element is not found).Ī final closing note: be wary when using include? on a Range, there are subtleties, so refer to the doc and compare with cover?. ![]() E.g: require 'set'ĪLLOWED_METHODS = Set[:to_s, :to_i, :upcase, :downcase So if you array is constant, for example, it is a good idea to use a Set instead. O(n)), while that lookup for a hash will be constant time (i.e O(1)). Note that if you have many values in your array, they will all be checked one after the other (i.e. OTOH, there is no in operator or #in? method in Ruby itself, even though it has been proposed before, in particular by Yusuke Endoh a top notch member of ruby-core.Īs pointed out by others, the reverse method include? exists, for all Enumerables including Array, Hash, Set, Range. There is an in? method in ActiveSupport (part of Rails) since v3.1, as pointed out by So within Rails, or if you require 'active_support', you can write: 'Unicorn'.in?() # => false
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |