3 ms·
Sure, simply do: module Enumerable def dollar(c) map.with_index{|a,i| a == c ? i : nil }.reject{|i| i.nil? } end end And then you
by tinco 12y ago
Sure, simply do:
module Enumerable
def dollar(c)
map.with_index{|a,i| a == c ? i : nil }.reject{|i| i.nil? }
end
end
And then you could do:
c = a.dollar("\n")
There is of course a reason this dollar method is not a part of the standard library. Its name makes no sense and it's oddly specific, how often would you want the indexes of matches to a character? Most modern languages don't like to work with indexes a lot, and in my day to day work I don't need indexes very frequently either. This I guess is just a thing that these finance/apl people do more often, so they have a specialized standard library.
(So when I said 'a neat way to do $' I meant it has no find_all_with_index method, which would make my implementation much cleaner)
- Widdershin 12y agoRegarding find_all_with_index, you can do: .find_all.with_index { |item, index| ... }
- dragonwriter 12y agoexcept .find_all.with_index passes the index to the predicate block, but still only returns a view of the matching elements from the list. What I think is being sought is more like: module Enumerable def find_indices each.with_index .find_all {|x,_| yield x} .map {|_,y| y} end end