1

For an input like 12,34,56;78,91;50,60;

I want to split the string by semi-colon delimit and then those strings split by comma delimit

ex:

puts "Input: "
input = gets.chomp
s_array = input.split(";")
for i in 0..s_array.size
    puts s_array[i].split(",")
end

It will successfully print with puts but after I get an error

undefined method 'split' for nil:NilClass <NoMethodError>

Whats the reason for this error?

1
  • This is not what you've asked for, but you might find it of interest: "12,34,56;78,91;50,60;".split(/[,;]/) #=> ["12","34","56","78","91","50","60"]. Commented Feb 18, 2014 at 3:21

2 Answers 2

2

Change .. for ...

for i in 0...s_array.size

Creating a range with .. is inclusive, while ... is not, e.g.

1..5  # => 1,2,3,4,5
1...5 # => 1,2,3,4

So the variable i overflows the array, in your case if the array size is 5, array_s[5] will be nill.

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

1 Comment

@user1763861, you should accept this question as correct, then.
2

A more rubyish approach is:

input.split(";").each { |x| puts x.split (",") }

You should use Array#each, it is not rubyish to use for and there are very few cases where for loop is required in place of each in ruby and the for keyword delegates to each even when used.

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.