Helpful Information
 
 
Category: Ruby Programming
Array problems

Hello!
Hi, im having problems with "arrays".
I know how to access the info inside an array and whatnot but what im having problems with is i dont know how to assign info to a blank array.

Im taking the Tutorials from
pine.fm(add a www to that, it wont let me add because im new to the forum) Programming , lesson 7
And on the very bottom of the tutorial it suggest that i create a program that would let you type in words (one per line), then when a blank space is entered it would list all the words you had put in but in alphabetical order.

The only problems im having is with creating the blank array and then having the input data put into the blank array . lol
I know in order to do this i know i have to use the .push method, but im just confused and wondering if someone could explain what to do, OR just show me a working code.

Thank you!
(oh also, if you havent guessed im a programming noob. ><)

You can either declare an array using Array.new, or assign it to an empty array instance []:


words = Array.new

or

words = []


As for the rest of the code, it is not too hard to write :)


#!/usr/bin/env ruby

words = Array.new

# Get list of words from the user
word = gets.chomp
while word != ''
words.push word
word = gets.chomp
end

# Sort the array
sortedwords = words.sort

# Print it out
sortedwords.each do |word|
puts word
end


and if you don't want to declare a separate sorted array, you can use words.sort! instead (note the ! at the end of the function name. In ruby, functions ending with ! end up modifying the object directly, instead of returning a copy)


#!/usr/bin/env ruby

words = Array.new

# Get list of words from the user
word = gets.chomp
while word != ''
words.push word
word = gets.chomp
end

# Sort the array
words.sort!

# Print it out
words.each do |word|
puts word
end

Thanks alot!
And also thanks alot for explaining it to me, i really appreciate you spending the time to do it.

Oh i see what i was putting wrong
i had put




words = Array.new


word = gets.chomp
while word != ''
words.push= word
word = gets.chomp
end


sortedwords = words.sort


sortedwords.each do |word|
puts word
end


Haha come to show how one little symbol can mess it all up.
: ]










privacy (GDPR)