如何在Ruby中檢查數組元素是否爲空?如何在Ruby中檢查數組元素是否爲空?
passwd.where { user =~ /.*/ }.uids
=> ["0", "108", "109", "110", "111", "112", "994", "995", "1001", "1002", "", "65534"]
如何在Ruby中檢查數組元素是否爲空?如何在Ruby中檢查數組元素是否爲空?
passwd.where { user =~ /.*/ }.uids
=> ["0", "108", "109", "110", "111", "112", "994", "995", "1001", "1002", "", "65534"]
不知道你想要什麼用它做,但也有相當多的這種貓的皮膚的方法。更多信息將有助於縮小它的一些...
["0", "108", "109", "110", "111", "112", "994", "995", "1001", "1002", "", "65534"].map { |v| v.empty? }
=> [false, false, false, false, false, false, false, false, false, false, true, false]
["0", "108", "109", "110", "111", "112", "994", "995", "1001", "1002", "", "65534"].each_with_index { |v,i| puts i if v.empty? }
10
我需要檢查空數組的索引值,並將其存儲在像下面的代碼檢查userid在linux中的變量中。描述passwd.where {user =〜/.*/} .uids做 它的(「長度」){should_not eq 0} 結束 –
這些測試的空虛:
'foo'.empty? # => false
''.empty? # => true
[1].empty? # => false
[].empty? # => true
{a:1}.empty? # => false
{}.empty? # => true
測試,看是否在數組中的元素爲空,將使用類似的測試:
['foo', '', [], {}].select { |i| i.empty? } # => ["", [], {}]
['foo', '', [], {}].reject { |i| i.empty? } # => ["foo"]
,或者使用速記:
['foo', '', [], {}].select(&:empty?) # => ["", [], {}]
['foo', '', [], {}].reject(&:empty?) # => ["foo"]
使用空?如果數組包含零,將導致崩潰 – s1mpl3
這是真的,但是OP僅指定了對「空」節點而不是「無」節點的關注。 –
arr = [ "0", "108", "", [], {}, nil, 2..1, 109, 3.2, :'' ]
arr.select { |e| e.respond_to?(:empty?) && e.empty? }
#=> ["", [], {}, :""]
任何元素?所有元素?沒有? – spickermann