ALH
ALH

Reputation: 85

Return length of strings in array with ruby

I'm a beginner to programming and I was given this problem to solve with ruby:

Given an array containing some strings, return an array containing the length of those strings. You are supposed to write a method named 'length_finder' to accomplish this task.

I wrote:

def length_finder(input_array)
    a = [ ]
    input_array.each { |n| puts n.length.to_i }
    a << n
    a
end

I got an error undefined local variable or method `n'. What's wrong with the code?

Upvotes: 1

Views: 4915

Answers (5)

Shagun Agarwal
Shagun Agarwal

Reputation: 1

Using Map method of Ruby gives one liner solution -

def length_finder(input_array)
  input_array.map { |s| s.length }
end

Upvotes: 0

Abdul Baig
Abdul Baig

Reputation: 3721

what you exactly need is just the following three lines of code:

def array_length(input_array)
  length = []
  input_array.each{ |a| length << a.length}
  length
end

Upvotes: 0

Saurabh
Saurabh

Reputation: 73589

First looking at your error, if you look closely, scope of n is only in each block, however you are trying to use it outside it's scope, thats why you are getting this error and second mistake is in a you should be appending n.length, which you want in the output, correct these two and you got a working code:

def length_finder(input_array)
    a = [ ]
    input_array.each { |n| puts n.length.to_i
                           a << n.length }
    a
end

however, this can be done in one line, using map or inject and the fact that ruby returns the output of last executing statement in a function. I will encourage you the try the one line solution for this.

Upvotes: 0

pjs
pjs

Reputation: 19853

Since this is an assignment, I won't give a direct answer to your problem. Instead, I'll show something similar. Suppose you wanted to create an array consisting of the first character of each word in a given array:

def first_char(x)
  x.map {|s| s[0]}
end

y = first_char(["abc", "xyz", "def"])      # y => ["a", "x", "d"]

Replace s[0] with a suitable manipulation for your problem.

Try this (and your own method) in irb, the interactive Ruby environment. Exploring is one of the best ways to learn, and irb makes exploring easy.

Upvotes: 2

Saturn
Saturn

Reputation: 18139

Following your particular approach, it should be

def length_finder(input_array)
    a = []
    input_array.each do |n|
        a << n.length
    end
    a
end

In your code, you are defining n inside a block and printing its size. You don't want to print its size. You want to put it in a. You get an error saying it is undefined because you are doing a << n outside the scope.

Upvotes: 1

Related Questions