Charlie Davies
Charlie Davies

Reputation: 1834

Select nested array in array from an arugment in Ruby

I have an array:

foo = [[51, 05,1.0],[51,979,0.18]]

What I would like to do is take this array and select all nested arrays that have the last value less than 1. So the output from the above would be

result = [[51,979,0.18]]

I have tried:

foo.select { |p| p.last < 1 }

But I get the error:

NoMethodError (undefined method `last' 

The array is much larger than just two but I have listed the above as en example. I thought .select would be right, but I can not get it to work.

Upvotes: 0

Views: 1830

Answers (4)

jack
jack

Reputation: 172

If you think bad values may exist in your data, it's worth protecting against them:

foo = [ [51, 05,1.0], [51,979,0.18], 4, nil, {:foo => :bar} ]

foo.select do |x|
    if (x.respond_to?(:last))
        x.last < 1
    else
        # the warn call evaluates to nil, thus skipping this element
        warn("#{x.class} does not respond to method last")
    end
end

Upvotes: 2

Maksim Ravnovesov
Maksim Ravnovesov

Reputation: 273

what about this ?

foo.select { |p| p.at(-1) < 1 }

Upvotes: 1

Mgrandjean
Mgrandjean

Reputation: 317

you were so close! instead of p.last use p[-1]

so

foo.select{ |p| p[-1] < 1}

Upvotes: 1

Waynn Lue
Waynn Lue

Reputation: 11385

Your code works for me.

irb(main):007:0> foo = [[51, 05,1.0],[51,979,0.18]]
=> [[51, 5, 1.0], [51, 979, 0.18]]
irb(main):008:0> foo.select { |p| p.last < 1 }
=> [[51, 979, 0.18]]

Upvotes: 3

Related Questions