From: "David A. Black" Date: 2009-04-27T19:19:18+09:00 Subject: Re: Deleting numbers in array Hi -- 7stud -- wrote: > 7stud -- wrote: >> Clayton Lane wrote: >>> David A. Black wrote: >>>> Hi -- >>>> >>>> Clayton Lane wrote: >>>>> I'm new to Ruby and unsure how to delete numbers in an array. I have an >>>>> array filled with numbers from 1 to 100. If I use nums.delete_if {|x| x >>>>> == 9 }, it will delete 9, but I want to remove any number containing 9. >>>>> For example, 19, 39, 92, 99 etc. I tried using a wildcard, but it didn't >>>>> work. I'm sure theres an easy command to do it, but I wasn't able to >>>>> find it on in Ruby documentation. I also want to remove numbers >>>>> containing 0,6,7, and 8 as well. Any help would be greatly appreciated. >>>> You're pretty much going to have to convert the numbers to strings. For >>>> example: >>>> >>>> array.delete_if {|x| x.to_s[/[06789]/] } >>>> >>>> >>>> David >>> Wow! Ruby is so good! I'm unsure of how to do this final step too. If >>> any numbers don't contain 1, remove them. Any ideas? >> arr = [51, 52, 20, 36, 79] >> result = arr.delete_if {|x| x.to_s[/[06789]/]} >> p result >> >> --output:-- >> [51, 52] >> >> result = arr.delete_if do |x| >> str = x.to_s >> str[/[02345]/] and not str[/1/] >> end >> p result >> >> --output:-- >> [51] > > lol. I screwed that up! I guess it was easier for me in C++ than ruby. > Hmm...for a ruby solution, I find that I have to use the same structure > as the C++ program: > > arr = [51, 52, 22, 20, 36, 79] > result = arr.delete_if {|x| x.to_s[/[06789]/]} > p result > > result = arr.delete_if do |x| > str = x.to_s > > if str[/06789/] > true #delete > elsif not str[/1/] > true #delete > else > false #keep > end > > end > p result > > --output:-- > [51, 52, 22] > [51] You're working much too hard :-) I'm not sure whether the OP only cares about the 1's, or wants to do both tests, but assuming the latter: arr.delete_if {|x| s = x.to_s; s[/[06789]/] ||! s[/1/] } David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now out in PDF: The Well-Grounded Rubyist (http://manning.com/black2) "Ruby 1.9: What You Need To Know" Envycasts with David A. Black http://www.envycasts.com