分配给数组并替换出现的nil值 [英] Assign to an array and replace emerged nil values

查看:74
本文介绍了分配给数组并替换出现的nil值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候!

按如下所示为数组分配值时,如何用0替换nil?

When assigning a value to an array as in the following, how could I replace the nils by 0?

array = [1,2,3]
array[10] = 2
array # => [1, 2, 3, nil, nil, nil, nil, nil, nil, nil, 2]

如果无法分配,那以后我该怎么做呢?我想到了array.map { |e| e.nil? ? 0 : e },但是...

If not possible when assigning, how would I do it the best way afterwards? I thought of array.map { |e| e.nil? ? 0 : e }, but well…

谢谢!

推荐答案

没有内置函数可以替换数组中的nil,因此,map是可行的方法.如果较短的版本会让您更快乐,则可以执行以下操作:

There is no built-in function to replace nil in an array, so yes, map is the way to go. If a shorter version would make you happier, you could do:

array.map {|e| e ? e : 0}

这篇关于分配给数组并替换出现的nil值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆