1

I'd like to delete an item in my loop i have a array of instance of my class, and i need sometimes to delete this items from my array

class Test
    attr_reader :to_del
    def initialize(str)
        @to_del = str
    end
end

tab = Array.new

a = Test.new(false)
b = Test.new(true)
c = Test.new(false)

tab.push(a)
tab.push(b)
tab.push(c)

for l in tab

    if l.to_del == true
        l = nil
    end

end

p tab

any idea ?

1
  • Note you can just write tab = [Test.new(false), Test.new(true), Test.new(false)]. As you gain experience with Ruby you'll find that for is very rarely used. (I've never used it.) That's because it's almost always better to employ a method that enumerates the elements of the receiver (here an array), as has been done by in both answers so far. Commented Jun 23, 2015 at 17:07

2 Answers 2

2

For inplace deletion:

tab.reject! { |l| l.to_del }

to return just a cleared array:

tab.reject &:to_del

The whole code is php-smelled. I would go with:

tab = (1..3).map { [true,false].sample }.map { |e| Test.new e }
tab.reject &:to_del
Sign up to request clarification or add additional context in comments.

12 Comments

And there's the fancy tab.reject!(&:to_del) shortcut.
@Max not only is it "fancy" Symbol#to_proc is actually faster than using an explicit block.
@engineersmnky Wrong. The behavior varies. Benchmark.bm { |x| x.report { n.times { [1,2,3].map { |i| i.to_s } } } ; x.report { n.times { [1,2,3].map &:to_s } } }[2.39, 2.71]. Please don’t make unfounded declarations.
I prefer Array.new(3) { ... } or 3.times.map { ... } to (1..3).map { ... } since the indices aren't important.
@mudasobwa This isn't code golf. 3.times and Array.new(3) are more semantic.
|
1

You can use Array#delete_if.

Check this out:

tab
#=> [#<Test:0x00000007548768 @to_del=false>, #<Test:0x000000074ea348 @to_del=true>, #<Test:0x000000074b21a0 @to_del=false>]
tab.delete_if {|x| x.to_del}
#=> [#<Test:0x00000007548768 @to_del=false>, #<Test:0x000000074b21a0 @to_del=false>]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.