0

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.

2
  • 3
    Get from where? For what? That's not a "multi-dimensional array", it's a hash with array values, at least so far. Commented Apr 14, 2013 at 1:58
  • @DaveNewton I edited my question, maybe its more clear? I guess its not a multi dimension array yet, but would like to get some kind of basis, if I have to do more Commented Apr 14, 2013 at 2:30

3 Answers 3

1

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']}

Sign up to request clarification or add additional context in comments.

1 Comment

No, you need to put the curly braces around it { and } instead of normal array ones. If you have the => you need curly braces. E.g. @array = {'apple'=>['tasty', 'red', 'round'], 'cereal' => ['milk', 'breakfast'], 'name' => ['tags']}
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.