ruby奇技淫巧 之 利用Fixnum的upto和downto方法来遍历数组

来源:互联网 发布:在c语言中随机数函数是 编辑:程序博客网 时间:2024/06/02 01:40
ruby奇技淫巧 之 利用Fixnum的upto和downto方法来遍历数组
arr = "1,2,3".split(',')
arr.map!{
|item| item = item.to_i} #一般可以用map!方法来改变原数组内容
0.upto(arr.length-1){|idx|arr[idx] = arr[idx].to_s} #再将数组内容改回字符串形式 使用upto方法


fixnum对象的upto和downto方法,可以很方便的作为访问一个数组的索引。

其实也可以这样做
(0..arr.length-1).each{|n| arr[n] = arr[n].to_i}


总之ruby是想怎么写就怎么写 非常方便
0 0
原创粉丝点击