Re: Quiz #65, Principle of Great Surprise, and Array.delete sledgehammer
- From: ara.t.howard@xxxxxxxx
- Date: Sun, 5 Feb 2006 06:10:21 +0900
On Sun, 5 Feb 2006, Dave Howell wrote:
I thought I was actually going to enter my first RubyQuiz, but I've spent three times as much time trying to get Ruby to stop surprising me as I have trying to implement my algorithm, and I've had to abandon my effort since I don't have the time to spend. Sigh.
Can somebody explain to me how I'm supposed to delete a *single* element from an array based on equivalence with an object? and get back said array with said element deleted?
In other words....
ar = [1, 2, 3, 8, 15, 15, 8]
ar.delete_one_element!(15)
=> [1, 2, 3, 8, 15, 8]
ar.delete_one_element!(14)
=> [1, 2, 3, 8, 15, 15, 8]
ar.delete_one_element!(nil)
=> [1, 2, 3, 8, 15, 15, 8]
I did find so many different ways of not doing this....
Too enthusiastic....
ar.delete(15)
=> 15
ar
=> [1, 2, 3, 8, 8]
Right results, wrong output...
ar.slice!(ar.index(15))
=> 15
ar
=> [1, 2, 3, 8, 15, 8]
and also surprised me by not handling 'nil' as I wanted...
ar.slice!(ar.index(13))
TypeError: no implicit conversion from nil to integer
from (irb):8:in `slice!'
from (irb):8
I mean, this seems so, er, obvious! "Please find one instance of this object in the array, and return to me the array without that object. If the array doesn't have that object, then just give the array back to me."
Why isn't that the Ruby Way? What am I missing here?
Help?
harp:~ > cat a.rb
class Array
def remove(*args) replace(self - args) end
end
a = %w( a b b )
p a.delete_if{|x| x == "b"}
a = %w( a b b )
p(a.delete("b") && a)
a = %w( a b b )
p a.select{|x| x != "b"}
a = %w( a b b )
p a - ["b"]
a = %w( a b b c )
p a.remove("b", "c")
harp:~ > ruby a.rb
["a"]
["a"]
["a"]
["a"]
["a"]
there are probably more ways.
hth.
-a
--
happiness is not something ready-made. it comes from your own actions.
- h.h. the 14th dali lama
.
- Follow-Ups:
- Re: Quiz #65, Principle of Great Surprise, and Array.delete sledgehammer
- From: Dave Howell
- Re: Quiz #65, Principle of Great Surprise, and Array.delete sledgehammer
- References:
- Quiz #65, Principle of Great Surprise, and Array.delete sledgehammer
- From: Dave Howell
- Quiz #65, Principle of Great Surprise, and Array.delete sledgehammer
- Prev by Date: Re: Quiz #65, Principle of Great Surprise, and Array.delete sledgehammer
- Next by Date: Re: Extract hash into local variables?
- Previous by thread: Re: Quiz #65, Principle of Great Surprise, and Array.delete sledgehammer
- Next by thread: Re: Quiz #65, Principle of Great Surprise, and Array.delete sledgehammer
- Index(es):
Relevant Pages
|