Request Dev Services »

theDevTip.com

Loops && Arrays with Ruby? (demo program)

Some Trivia: Ruby is said to resize the array dynamically, so it is not typically necessary to establish the size with it’s creation. In many cases it probably wouldn’t be the best idea to resize, as its usually counterproductive for dynamic or scaling content/data.

“Dynamic arrays benefit from many of the advantages of arrays, including good locality of reference and data cache utilization, compactness (low memory use), and random access. They usually have only a small fixed additional overhead for storing information about the size and capacity. This makes dynamic arrays an attractive tool for building cache-friendly data structures.” – https://en.wikipedia.org/wiki/Dynamic_array#Bounded-size_dynamic_arrays_and_capacity

A potential con of dynamic arrays could be that in some languages the arrays do not actually store or contain the actual data or value but rather a reference of.

Sample Program using arrays, loops, and organizing output with ruby.

#Below I am prompting the user to enter a number between 1 and 10 (inclusively), then I read that number into an appropriately named variable.

loop do
 print "Enter a number between 1 and 10: "
 s = gets.chomp.to_i
 #I then test and see if that the number lies in the appropriate range.
 if (1..10).include?(s)
 #I use the acceptable number entered by the user to create an array with that number of elements.

 arr = [""] * s
 i = 0
 #I write a loop which will run through a number of iterations equal to the size of the array. Each time through, I prompt the user to enter a text string - type of something (ie. coffee).

 while i < arr.length
   print "Define that many types of coffee drinks: "
   coffee = gets.chomp
   arr[i] = coffee
   i += 1
 end

# puts arr.join(", ")
puts arr.sort{ |x, y| y <=> x }.each_slice(3){ |e| puts "#{e.join(" - ")}\n"}
puts arr.each_slice(3) { |part| puts part.join(" - ") + "\n" }
puts arr.sort{ |y, x| y <=> x }.each_slice(3){ |e| puts "#{e.join(" - ")}\n"}
#Once the array is entered, I display the contents of the array three items to a line. I then, also, separate the array elements with dashes - 

break
else
  puts "Number entered is outside specified range, try again."
break
 end
end

sample output

About the Author
Cameron Cashwell Web Developer
I build websites, web apps, and software. Wanna work together? Let's chat about your project!

Leave a Reply

avatar
  Subscribe  
Notify of