Array Functions

本文深入探讨了Ruby编程语言的基本操作、数据结构处理、数组操作、条件选择与迭代、数组筛选与转换等核心内容,提供了丰富的示例和应用场景,旨在帮助开发者提升编程效率和代码质量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值