0
Persoane = []
Nume = gets
Persoane.push Nume.split(",")
puts Persoane.sort

I am trying to get an user to input carachters that get split into substrings which get inserted in an array, then the program would output the strings in alphabetical order. It doesnt seem to work and I just get the array's contents, like so:

PS C:\Users\Lenovo\Desktop\Ruby> ruby "c:\Users\Lenovo\Desktop\Ruby\ruby-test.rb"
Scrie numele la persoane
Andrei,Codrin,Bradea
Andrei
Codrin
Bradea
PS C:\Users\Lenovo\Desktop\Ruby> 

4 Answers 4

2

you can do this :

Nume = gets
puts Nume.split(",").sort

or in 1 line

array = gets.chomp.split(",").sort
Sign up to request clarification or add additional context in comments.

Comments

0

The error is because of your use of push. Let's assume that you define the constant Nume by

Nume='Andrei,Codrin,Bradea'

Then, Nume.split(',') would return the Array ['Andrei', 'Codrin', 'Bradea']. When you do a Persoane.push, the whole array is added to your array Persoane as a single element. Therefore, Persoane contains only one Element, as you can verify when you do a

p Persoane

If you sort a one-element array, the result will also be just that one element - there is nothing to sort.

What you can do is using concat instead of push. This would result in Persoane being a 3-element array which can be sorted.

Comments

0

I'm not sure you need use constants here

If you don't need keep user input and use it somewhere, you can just chain methods like this

persons = gets.chomp.split(",").sort

1 Comment

As extraneous whitespace is likely unwanted on the individual names, I would suggest either mapping &:strip on the resulting Array. If you do that, the call to #chomp is unnecessary. Either that or .split(/\s*\,\s*/)
0

For something a little different, let's not split at all.

people = gets.scan(/[^,]+/).map(&:strip).sort

This will avoid problems like multiple commas in a row yielding empty strings. Of course, you could also avoid that with:

people = gets.split(/\,+/).map(&:strip).sort

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.