On 24/10/2006, at 1:02 PM, Seth E. wrote:
> Li Chen wrote:
>
>> I have an array of [1,2,''] I want change it to [1,2]. I check the
>> document about Array but I can't find a way to remove the empty
>> element.
>> Any comments?
>
> How about this?
>
> irb(main):201:0> arr = [1,2,'']
> => [1, 2, ""]
> irb(main):202:0> arr -= ['']
> => [1, 2]
If you just want to delete empty strings (as opposed to strings
containing only whitespace), this would seem the obvious way:
irb(main):003:0> a = [1, 2, '', 3, '']
=> [1, 2, "", 3, ""]
irb(main):004:0> a.delete ''
=> ""
irb(main):005:0> a
=> [1, 2, 3]
If you want to delete any whitespace-only strings as well:
irb(main):002:0> a = [1, 2, '', 3, ' ']
=> [1, 2, "", 3, " "]
irb(main):007:0> a.delete_if {|s| s =~ /^\s*$/ }
=> [1, 2, 3]
Pete Yandell
http://notahat.com/