1

I am trying to figure out how to get the length of an array's value(index?) For some reason it is returning 1,0,0 and I am clueless why. Can anyone explain what I am doing wrong please? FYI this is from RubyMonk. I am trying to solve it without getting the answer..just need a little boost to figure out what im doing wrong

def length_finder(input_array)
 output= []
   input_array.length.times do |x|
    output << input_array.length[x]
   end
 return output
end
2
  • 2
    You might also want to try Array.each, which is a cleaner way to loop through the items (although kudos on the clever use of times) Commented Nov 3, 2011 at 21:08
  • 1
    You need the length of the array or the length of every element in the array? Commented Nov 3, 2011 at 21:10

3 Answers 3

4

Shouldn't it be:

output << input_array[x].length

Here you're using the Bit reference method.

Some more Ruby style:

def length_finder(input_array)
  input_array.map(&:length)
end
Sign up to request clarification or add additional context in comments.

Comments

3

That's very much over complicated and not idiomatic at all. Try this:

def length_finder(input_array)
  input_array.map { |x| x.size }
end

That should give you a new array, with the size of each child array as a member.

2 Comments

nice answer, +1 for the added value
Nice.. but OP didn't want an answer answer, just a fix to his question :)
0
def length_finder(input_array)
  output = []
  input_array.each do |x|
    output << x.length
  end
  return output
end

my_array = length_finder(["first", "second", "third", "forth"])

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.