0

I am trying to iterate through an array in Ruby. I using eachmethod but getting the following error message: NoMethodError: undefined method ``each' for "1, 2":String.

I am using jruby-1.6.7. Not sure if that is the problem.

Here is the code:

#!/usr/bin/ruby

puts "Select one of these.\n1. ABC\n2. DEF\n3. GHI\n"

schemas = gets.chomp

len = schemas.size

puts schemas.split(",")

puts schemas[0..len]

schemas.each {|x| puts x}

I need some guidance with iterating through a simple array in Ruby?

Thanks.

4
  • I'm not seeing how schemas is an array. If you want to wrap a string to act as an array, then do Array(schemas).each Commented Nov 10, 2014 at 3:16
  • 1
    You do schemas.split(",") but schemas not changes. You can do schemas = schemas.split(",") then use schemas.each {} Commented Nov 10, 2014 at 3:26
  • That worked. I did schemas = schemas.split(",") and that worked. Thank you for the clear explanation. Commented Nov 10, 2014 at 4:19
  • Also len has the size of string which should be the size of the array. so len = schemas.split(",").size should be what you must have to iterate through the array of the specified length. Commented Nov 10, 2014 at 5:39

2 Answers 2

1

You were on the right track:

schemas = gets.chomp
# => "1, 2"

# save the result of split into an array
arr = schemas.split(",")
# => [1, 2]

# loop the array
arr.each { |schema| puts schema }
# => 1
# => 2

You can also do this in one line, though the array won't get saved anywhere.

schemas = gets.chomp
schemas.split(",").each { |schema| puts schema }
# => 1
# => 2
Sign up to request clarification or add additional context in comments.

Comments

0

You have the right idea, however you are calling the Array#each method on a String.

schemas = gets.chomp
puts schemas.split(",")

It's true that the String#split method converts a string to an array, however you never actually converted the data type. schemas is still recognized as a string.

What you could do is

schemas = schemas.split(",")

Then

schemas.each{|x| puts x}

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.