在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
n=[1,2,3,nil,nil] p n n1=n.compact p n1 n2=n.compact! p n2 p n
主要是交流,水平有限,喜欢研究,多多包涵。 arr=[1,2,3] n=arr << arr p n 输出: [1, 2, 3, [...]] 分析: arr=[1,2,3] p arr.at(2) p arr[2] 其实:at比[]方法要效率一点,因为它不接受range参数 require 'benchmark' n=(1..1000000).to_a l=n.length Benchmark.bm do |bm| bm.report("at") do i=0 while i< l n.at(i) i+=1 end end bm.report("[]") do i=0 while i< l n[i] i+=1 end end end 输出: user system total real at 0.610000 0.000000 0.610000 ( 0.609000) [] 0.625000 0.000000 0.625000 ( 0.625000) 结论:大数组的获取元素首选at
n=[1,2,3,nil,nil] p n n1=n.compact p n1 n2=n.compact! p n2 p n 删除数组中nil的元素,带!返回数组本身,如果数组中没有nil,不带!返回Nil,带!返回数组本身。 n=[1,2,3,nil,nil] p n.delete(nil) p n require 'benchmark' n=Array.new(100000000,nil) n1=Array.new(100000000,nil) Benchmark.bm do |bm| bm.report("delete") do n.delete(nil) end bm.report("compact") do n1.compact end end user system total real delete 0.718000 0.016000 0.734000 ( 0.735000) compact 1.360000 0.062000 1.422000 ( 1.453000) 结论:删除元素首选 delete require 'benchmark' n=(1..100000).to_a Benchmark.bm do |bm| bm.report("each") do n.each do |d| d end end bm.report("for") do for i in n i end end bm.report("while") do i=0 while i< n.length n[i] i+=1 end end end user system total real each 0.015000 0.000000 0.015000 ( 0.015000) for 0.016000 0.000000 0.016000 ( 0.016000) while 0.078000 0.000000 0.078000 ( 0.078000) 结论:each 很效率 n=[1,2,3] n1=[4,5,6] n2=[n1,n] p n2 p n2.flatten # [[4, 5, 6], [1, 2, 3]] [4, 5, 6, 1, 2, 3] 5.sort与自定义方法比较 require 'benchmark' n=(1..100).to_a n1=(23..89).to_a n2=(900..3003).to_a n=n2+n1+n #自定义方法是网上找的 def bubble_sort(arr) 1.upto(arr.length-1) do |i| (arr.length-i).times do |j| if arr[j]>arr[j+1] arr[j],arr[j+1] = arr[j+1],arr[j] end end end arr end Benchmark.bm do |bm| bm.report("sort") do n.sort end bm.report("personal") do bubble_sort(n) end end user system total real sort 0.000000 0.000000 0.000000 ( 0.000000) personal 3.109000 0.109000 3.218000 ( 3.220000) 结论:坑爹啊,ruby自带方法还是很强大的,首选自带方法sort |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论