0

I'm new to Ruby. I'm trying to learn the dos and don'ts by making little programs. This program is a little redundant, but I wanna better myself with the syntax of the language.

Anyways, so I'm trying to create a little program that will ask the user for an amount of people. This amount of people will then reference the size of the array, then the program will ask the user to enter the names for each element in the array (which ALL be "nil" values since the new array's elements will be empty). Finally, I would want to print back the array to the console to see the completed elements.

However, I'm getting an error saying "Line 10: TypeError occured. No implicit conversion from nil to integer". My code is not 100% done. I'm still trying to add more stuff to it, but I want to troubleshoot this error first before I go about doing that. Anyone out there willing to help me out ?

Here's the code

def Array_Maker 
  puts "How many people would you like to enter? : "
    num = gets.chomp.to_i

    nameArray = Array.new(num)

  puts "\nEnter the names of the people you wish to add: "

    nameArray.each do |x|
    nameArray[x] = gets.chomp.to_s
  end

    nameArray.each do |x| 
      puts x
  end
end  

Array_Maker()

I'm probably doing this all wrong, but I'm trying...

1
  • You can write gets.chomp.to_i as gets.to_i and since gets.chomp is a string, .to_s in gets.chomp.to_s has no effect. Commented Jan 2, 2015 at 11:43

2 Answers 2

1

The line nameArray.each do |x| iterates over the array and x is set to the value of the array at each index.

A better way might be to build the array using a map method. Something like this:

def array_maker 
  puts "How many people would you like to enter? : "
    num = gets.chomp.to_i
  puts "\nEnter the names of the people you wish to add: "

  nameArray = num.times.map do
    gets.chomp.to_s
  end

  nameArray.each do |x| 
    puts x
  end
end  

array_maker()
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhh...So that's how you do it. I didn't seem too far off. Thank you so much!
1

nameArray.each do |x| In this loop, x is given the values of the Array which is nil

Try this.

for i in 0..num do
  nameArray[i] = gets.chomp.to_s
end

1 Comment

I'm gonna try this code to better my understanding aswell. Thank you so much!

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.