简体   繁体   中英

Multi-Dimensional Array in Ruby on Rails?

I'm wondering if its possible to do multidimensional arrays in rails?

I'd like to get something like to formulate some data:

apple => 'tasty', 'red', 'round'
cereal => 'milk', 'breakfast'
name => 'tags'

Where I'm trying to get the name-value pair where the right side is tags so when I call the name, I can get tags.

EDIT:

I currently have this

@array = ['apple', 'cereal', 'name']

But would like to add tags to these

@array = ['apple'=>['tasty', 'red', 'round'], 'cereal' => ['milk', 'breakfast'], 'name' => ['tags']]

I wanted to do something like this, so when I do a loop to output only the names, and the associated tags.

Like Dave Newton said above in the question's comments, it's called a hash, it's for things like key => value . Hash's can use Array's as values, Array's can use Hashes as values.

{apple: ['tasty', 'red', 'round'], cereal: ['milk', 'breakfast'], name: ['tags']}

What you want is called Hash , whose element are key-value pair. The key should be is string or symbol ;the value could be any object.

In you specific case, apple is the key, and ['tasty', 'red', 'round'] is the value.

Check out this link for more about Hash in Ruby.

Have you heard of YAML? You can put your data in YAML format in a file, read it in, and it automatically will create your hashes and arrays for you:

apple:
   - tasty
   - red
   - round
cereal:
   - milk
   - breakfast
name: tags

and then in ruby: require 'yaml'

file=YAML.load_file(filename)
file.each_pair do |key, value|
   ...etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM