FlapsMack
FlapsMack

Reputation: 31

Ruby pushing to a hash

I have a two part question and I apologize in advance if it is confusing at all. I'm trying to put user input into an empty hash. I know with an array you use the << to push the info to it. Is there a hash equivalent to this?

2nd part: Say I was just looping them the same question until a condition is met. The user input is going to be the value. Is there a way/method to make the key automatically change per the user input? So it would look something like: {str1 => "example string", str2 => "example string2", str3 => "example string3"}

Or is there a way to have ruby assign a key on its own?

Sorry again if the second part is confusing. I know an array would be better but the little challenge I am working is asking for a hash.

Upvotes: 3

Views: 5411

Answers (5)

SignorHarry
SignorHarry

Reputation: 44

Ok, it isn't array so '<<' can't be work.

You should use this:

your_hash = {}
hash_key = "x"
hash_value = "y"
your_hash[:hash_key] = hash_value

It's all.

Upvotes: 0

tadman
tadman

Reputation: 211590

If you don't care about indexing on a key, as a Hash is intrinsically a key/value store, you probably want a Set:

require 'set'

set = Set.new

set << gets.chomp

A set is like a keyless hash, it's an un-ordered collection of things but with the side benefit that lookups for elements in the set are quick and they're also automatically uniqued, adding the same thing twice has no effect.

The alternative here is to put something in the Hash with the value as the key and any other value as a placeholder:

values = { }

values[input.gets] = true

This is like a Set but is probably less efficient to use if you don't care about values.

Upvotes: 0

mrvncaragay
mrvncaragay

Reputation: 1260

Another way to add element to ruby hash store(key, value)

hash = {}
hash.store("first", 42)
hash #=> {"first"=>42}

Upvotes: 3

kcdragon
kcdragon

Reputation: 1733

Here are the two ways to add to a Hash

hash[str1] = "example string"
hash.merge!(str1 => "example string")

Upvotes: 0

max pleaner
max pleaner

Reputation: 26768

With an array you use << to push a single element.

With a hash you are tracking not one element but two (both the key and value).

So for example:

my_key = "foo"
my_val = "bar"
my_hash = {}
my_hash[key] = val

Sure, you can do this in a loop.

I would recommend RubyMonk to learn more about this but their website is down. So I can recommend this gist which shows some examples or simply read the Hash section of any ruby tutorial.

Upvotes: 2

Related Questions