From: Robert Klemme Date: 2011-09-18T20:30:08+09:00 Subject: Re: array.map! + delete_if possible ? On 17.09.2011 00:03, Kassym Dorsel wrote: > I have an array of strings that I need to modify. I either need to > replace the string or delete the entry altogether. irb(main):010:0> a = 10.times.to_a => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] irb(main):011:0> a.map! {|i| i.odd? ? i : nil}.compact! => [1, 3, 5, 7, 9] irb(main):012:0> a => [1, 3, 5, 7, 9] > The only way I have > been able to do this is : > > > arr.delete("") > > (0..arr.size).each do |i| arr.each_index do |i| > if arr[i].to_i == 1201 > arr[i]=arr[i].to_s[8..-1].gsub(/"[^"]*"/,'::').gsub(/".*/,"::") Maybe: arr[i] = arr[i].to_s[8..-1].gsub(/"[^"]*(?:"|\z)/,'::') Is this really what you want? First you convert all quoted sequences to "::" and then you remove everything after the single remaining quote to the end by "::"? > else > arr[i-1] = arr[i-1] + arr[i].to_s[4..-1].to_s.gsub(/\s*/,"") arr[i-1] << arr[i].to_s[4..-1].to_s.gsub(/\s*/,"") > arr[i]=nil > end > end > > arr.delete(nil) arr.compact! > Is there a better way ? First we should clarify what you are doing. As far as I can see you want to iterate the array and either modify element i or convert element i and append it to element i - 1. From this it is clear that you cannot use #map or #map! because those methods are intended to modify the current object. > Also inside the else I get char 4->-1 of a string, but then need to > explicitly change it into a string for gsub to work. Otherwise it gives > me an undefined method 'gsub' for nilNilClass error. So your statement that you have a String is not correct. You are probably experiencing this effect irb(main):017:0> s="123" => "123" irb(main):018:0> s[4..-1] => nil A bit of sample data would be helpful... Kind regards robert