Wednesday 15 February 2012

Dynamically Create Arrays in Ruby -


Is there a way to dynamically create an array in Ruby? For example, suppose I want to loop through the array of a book as a user input:

books = gets.chomp

User input:

  "The Great Gatesby, Crime and Punishment, Dracula, Fahrenheit 451, Pride and Prejudice, Sense and Sensibility, Slashhouse-Five, Adventures of Hucklebury Finn"  

I change it to an array:

  books_array = books.split (",")  

Now, Everybody User input for a book, I want to make Ruby to make an array. To do this, pseudo-code:

  x = 0 books_your counts.times do x + = 1 puts "Please weekly sales of # book_ar [x]} separated by commas. " Weekly_sali = gets.chomp.split (",") end  

Obviously this does not work. It will only define weekly_seal again and again . What is the method of creating a new array with each loop of the Times?

  weekly_sale = {} puts 'a list of books' book_list = gets Chomp books = book_list.split (',') books.each do | Book | Say, "Please input the weekly sales of # {book}, separated by commas." Weekly_sales [book] = gets.chomp.split (',') End  

In Ruby, there is a concept of a hash, which is a key / value pair. In this case, Weekly_sali hash is, we are using book names as keys, and value as array.

Instead of doing a small change in your code, instead of doing books, counts.times to define loop and then to define the array array elements with counter, through each collection to be repeated There is a very good way.


No comments:

Post a Comment