Ruby is a language that can be described by sexy. The following describes several iterative operations of sexy.
1. Each simple iteration each is a very common traversal operation in Ruby. It is a direct substitute for aging. If you need an index, you can use the each_with_index method.
words=%w(good god ruby sexy girl run)words.each do |word|puts wordend
2. Find finds the first qualified element for a single element. Find.
words=%w(good god ruby sexy girl run)words.find do |word|word.start_with? 'r'end=> "ruby"
3. Select select elements select all elements that meet the conditions.
words=%w(good god ruby sexy girl run)words.select do |word|word.start_with? 'r'end=> ["ruby", "run"]
4. The reject removing element removes some qualified elements, reject.
words=%w(good god ruby sexy girl run)words.reject do |word|word.start_with? 'r'end=> ["good", "god", "sexy", "girl"]
5. Map conversion elements convert each element, map.
words=%w(good god ruby sexy girl run)words.map do |word|word.capitalizeend=> ["Good", "God", "Ruby", "Sexy", "Girl", "Run"]
6. uniq uniquely removes equal elements, uniq.
words=%w(good god ruby sexy girl run run god Run)words.uniq=> ["good", "god", "ruby", "sexy", "girl", "run", "Run"]
You can also specify the comparison method in the block to customize the comparison object.
words=%w(good god ruby sexy girl run run god Run)words.uniq do |w|w.downcaseend=> ["good", "god", "ruby", "sexy", "girl", "run"]
7. group_by grouping element. This is really sexy, group_by. Group by initials:
words=%w(good god ruby sexy girl Run)words.group_by do |w|w.capitalize[0]end=> {"G"=>["good", "god", "girl"], "R"=>["ruby", "Run"], "S"=>["sexy"]}
8. sort_by: sort_by.
words=%w(good god ruby sexy girl Run)words.sort_by do |w|w.lengthend=> ["Run", "god", "sexy", "ruby", "girl", "good"]
9. Zip combination element combination traversal element, zip.
words=%w(good god ruby sexy girl Run)numbers=(11..16)symbols=%w(+ - * / = %)words.zip(symbols,numbers)=> [["good", "+", 11], ["god", "-", 12], ["ruby", "*", 13], ["sexy", "/", 14], ["girl", "=", 15], ["Run", "%", 16]]
10. The value of inject accumulation element accumulation is my favorite one, inject.
numbers=(1..10)numbers.inject do |memo,value|memo=memo+valueend=> 55
This is relatively simple. If you need to replace the keys and values of the hash table {A: 1, B: 2, C: 3, D: 1, that is, key-to-value, value-to-key, and repeated values are converted into keys, and the original keys are converted into list values.
tbl={a:1,b:2,c:3,d:1}tbl.inject({}) do |memo,(k,v)|memo[v]||=[]memo[v]<<kmemoend=> {1=>[:a, :d], 2=>[:b], 3=>[:c]}