0

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.

2
  • this code works, so probably one element in foo may is not an array at all. Commented Mar 9, 2012 at 11:43
  • Your error message should tell what class the receiver belongs to. Does it say that what you have is an array? And are you using an old version of Ruby? Commented Mar 9, 2012 at 11:45

4 Answers 4

3

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]]
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

so

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

Comments

1

what about this ?

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

2 Comments

can you think of any reason why i get NoMethodError (undefined method `at' for
@CharlieDavies obviously because it's not an Array. You need to specify more information. undefined method 'at' for what exactly? the rest of the error message is there, please show it to us. Also, this code is no different from yours. array.at(-1) array[-1] and array.last all do the same thing

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.