View Single Post
  #2 (permalink)  
Old 10-16-2007, 05:32 AM
mobilegeek mobilegeek is offline
D-Web Analyst
 
Join Date: Jun 2007
Posts: 205
mobilegeek is on a distinguished road
Smile Re: how to assign info to a blank array?

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

Code:
words = Array.new
or

Code:
words = []
As for the rest of the code, it is not too hard to write


Code:
#!/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)

Code:
#!/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
Reply With Quote