1. NEW
tar = [1,2,3,4,5]
arr = Array.new(4000){|i| 1+i }
# better spell:
arr = (1..4000).to_a
# use tap
tar = [].tap {|i| (1..3).to_a.each{|e| i << e}}
2.1 take
# Returns first elements
tar = arr.take(60)
2.2 first last
tar = arr.first
tar = arr.last
# first == take
tar = arr.first(60)
tar = arr.last(60)
2.3 slice
tar = arr[0..99]
tar = arr[0...99]
tar = arr[100..-1]
2.4 sample
# Choose random element(s)
tar = arr.sample
tar = arr.sample(2000).take(50)
3. split
ids = (1..100).to_a
a.each_slice(20) do |play_ids|
p play_ids
end
4. flatten uniq sort
tar = [[1,4,2],[1,4,3],[2,3,4]].flatten
tar = tar.uniq
tar = tar.sort
5.1 drop
DEL element(s) at the top front
tar = arr[0..50].drop(3)
5.2 push
Add element(s)
tar = [1,2,3].push(4)
# better spell:
tar = [1,2,3] << 4
# infinity agrs
tar = [1,2,3].push('sina', 3.14, (3..7), :s)
5.3 unshift
Add element(s) at the top front
6.1 each each_with_index || odd?
[1,2,3].each{|e| p e.odd?}
[1,2,3].each_with_index{|e,i| p "Array[#{i}] => #{e}"}
6.2 select VS map&collect
new_array's SIZE changed OR not
tar = [12,22,-34,-1,134,-43].select{|e| e>0}
tar.size
# map == collect
tar = [12,22,-34,-1,134,-43].collect{|e| e if e>0}
tar = [12,22,-34,-1,134,-43].map{|e| e if e>0}
6.3 map with index || compact
tar = [12,22,-34,-1,134,-43].enum_for(:each_with_index).map{|e,i| "#{i}: #{e}" if e>0}.compact
2D find
choise-1 arr.map{|e| e if e.title == 'ruby' }.compact.first
chiose-2 arr.find{|e| e.title == 'ruby' } http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-find