delete_unless in Array and Hash?

D

Daniel Schierbeck

Is there a reason why there doesn't exist a delete_unless method in
Array and Hash? I think it's quite handy. It's also easy to implement
(in ruby):

class Array
def delete_unless (&block)
delete_if { |element| not block.call(element) }
end
end

class Hash
def delete_unless (&block)
delete_if { |key, value| not block.call(key, value) }
end
end


Daniel
 
R

Robert Klemme

Daniel said:
Is there a reason why there doesn't exist a delete_unless method in
Array and Hash? I think it's quite handy. It's also easy to implement
(in ruby):

class Array
def delete_unless (&block)
delete_if { |element| not block.call(element) }
end
end

class Hash
def delete_unless (&block)
delete_if { |key, value| not block.call(key, value) }
end
end

It's even simpler to just invert the condition. I guess that's the
reason. You don't really gain much with this method. Taste differ but
there are peple who don't like "unless" at all... These are all
equivalent:

some_array.delete_unless {|x| x % 3 == 0}
some_array.delete_if {|x| x % 3 != 0}
some_array.delete_if {|x| not x % 3 == 0}
some_array.delete_if {|x| !(x % 3 == 0)}

Kind regards

robert
 
D

Daniel Schierbeck

Robert said:
It's even simpler to just invert the condition. I guess that's the
reason. You don't really gain much with this method. Taste differ but
there are peple who don't like "unless" at all... These are all
equivalent:

some_array.delete_unless {|x| x % 3 == 0}
some_array.delete_if {|x| x % 3 != 0}
some_array.delete_if {|x| not x % 3 == 0}
some_array.delete_if {|x| !(x % 3 == 0)}

Kind regards

robert

I still think it's more obvious, especially if you're calling a method
from the block, i.e. array.delete_unless { |x| is_fooish(x) }


Daniel
 
R

Robert Klemme

Daniel Schierbeck said:
I still think it's more obvious, especially if you're calling a method
from the block, i.e. array.delete_unless { |x| is_fooish(x) }

Well, as said people's tastes differ - I don't see much difference between
that and this:

array.delete_if { |x| !is_fooish(x) }

Btw, typically the method would be called fooish?().

Kind regards

robert
 
D

Daniel Schierbeck

Robert said:
Well, as said people's tastes differ - I don't see much difference
between that and this:

array.delete_if { |x| !is_fooish(x) }

Yes, and since some people prefer to use unless instead of a negated
"if" statement, I think we should provide that method. After all,
"unless" is already a part of the language.


Daniel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,950
Members
47,503
Latest member
supremedee

Latest Threads

Top