Creating a hash inside an array that contains hashes - ruby

Let me preface this by saying I am just starting to learn ruby...
I have any array that is made of hashes, and arrays nested within each other. It looks like this:
people =
[
{
"John Doe" => {
"phone" => "555-555-555",
"company" => "Company name",
"children" => [
"John",
"Jane",
"Annamarie"
]
},
"Jane Smith" => {
"phone" => "555-555-5555",
"company" => "company name",
"children" => [
"Steven"
]
}
}
]
How would I go about adding a new hash where the name of the person acts as a key, and the new hash is the value? E.g. I want to add "spouse" so the hash would look like this:
people =
[
{
"John Doe" => {
"phone" => "555-555-555",
"company" => "Company name",
"children" => [
"John",
"Jane",
"Annamarie"
],
"spouse" => "Jane Doe"
},
"Jane Smith" => {
"phone" => "555-555-5555",
"company" => "company name",
"children" => [
"Steven"
],
"spouse" => "John Smith"
}
}
]

You can use select to get the hash with "John Doe" as the key...
search_user = "John Doe"
person = people.select{|p| p.has_key?(search_user)}.first
person[search_user]['spouse'] = "Jane Doe" if person
The reason for if person on the last line is to handle the case that no "John Doe" was found.

Related

How do I convert an Array with a JSON string into a JSON object (ruby)

I have an Array whose content is as follow:
[
[0] {
"name" => “Mark”,
"id" => “01”,
"description" => “User”,
},
[1] {
"name" => “John”,
"id" => “02”,
"description" => “Developer”,
}
]
Note: right now each item of the Array is a Hash (not a string). That is to say that if I do puts myarray[0].class I get hash in return.
I would like to be able to create an object that I can reference as object[i].field.
For example I'd like to be able to get "Mark" by calling object[0].name or get "Developer" by calling object[1].description.
Is this possible? I have tried to leverage the .to_json method against my array but it doesn't quite give me what I need.
Thanks.
You can do use Struct to meet your need.
array = [
{
"name" => "Mark",
"id" => "01",
"description" => "User",
},
{
"name" => "John",
"id" => "02",
"description" => "Developer",
}
]
Customer = Struct.new(:name, :id, :description)
array_of_customers = array.map { |hash| Customer.new(*hash.values) }
array_of_customers[1].name # => "John"
array_of_customers[1].description # => "Developer"

ruby - how can I access an variable

I have this array:
{
:details=> [
{
"account" =>"",
"address" =>"",
"category" =>"send",
"amount" =>0.0,
"fee" =>0.0
},
{
"account" =>"payment",
"address" =>"SXX5kpEyF8w1oK913wVg2ZbJWpLmWnCgAU",
"category" =>"receive",
"amount" =>1.0
}
]
}
How can I access the second "address" element in ruby? When I do
address: detail[:address]
I get only the first one (which is empty).
How about:
data = {
:details=> [
{
"account" =>"",
"address" =>"",
"category" =>"send",
"amount" =>0.0,
"fee" =>0.0
},
{
"account" =>"payment",
"address" =>"SXX5kpEyF8w1oK913wVg2ZbJWpLmWnCgAU",
"category" =>"receive",
"amount" =>1.0
}
]
}
And then(Because, you never know the sequence of Hashes inside Array):
data[:details].detect{|d| !d['address'].empty? }['address']
Just address the second element of array
obj = {
:details => [
{
"account" =>"",
"address" =>"",
"category" =>"send",
"amount" =>0.0,
"fee" =>0.0
},
{
"account" =>"payment",
"address" =>"SXX5kpEyF8w1oK913wVg2ZbJWpLmWnCgAU",
"category" =>"receive",
"amount" =>1.0
}
]
}
obj[:details][1]['address']
Here is online REPL: http://repl.it/ZZm
Using the inject method you can get all of them like this:
[21] pry(main)> results = []
=> []
[22] pry(main)> json[:details].inject { |sum, k| results << k["address"] }
=> [["SXX5kpEyF8w1oK913wVg2ZbJWpLmWnCgAU"]]

How do I access JSON array data?

I have the following array:
[ { "attributes": {
"id": "usdeur",
"code": 4
},
"name": "USD/EUR"
},
{ "attributes": {
"id": "eurgbp",
"code": 5
},
"name": "EUR/GBP"
}
]
How can I get both ids for futher processing as output?
I tried a lot but no success. My problem is I always get only one id as output:
Market.all.select.each do |market|
present market.id
end
Or:
Market.all.each{|attributes| present attributes[:id]}
which gives me only "eurgbp" as a result while I need both ids.
JSON#parse should help you with this
require 'json'
json = '[ { "attributes": {
"id": "usdeur",
"code": 4
},
"name": "USD/EUR"
},
{ "attributes": {
"id": "eurgbp",
"code": 5
},
"name": "EUR/GBP"
}]'
ids = JSON.parse(json).map{|hash| hash['attributes']['id'] }
#=> ["usdeur", "eurgbp"]
JSON#parse turns a jSON response into a Hash then just use standard Hash methods for access.
I'm going to assume that the data is JSON that you're parsing (with JSON.parse) into a Ruby Array of Hashes, which would look like this:
hashes = [ { "attributes" => { "id" => "usdeur", "code" => 4 },
"name" => "USD/EUR"
},
{ "attributes" => { "id" => "eurgbp", "code" => 5 },
"name" => "EUR/GBP"
} ]
If you wanted to get just the first "id" value, you'd do this:
first_hash = hashes[0]
first_hash_attributes = first_hash["attributes"]
p first_hash_attributes["id"]
# => "usdeur"
Or just:
p hashes[0]["attributes"]["id"]
# => "usdeur"
To get them all, you'll do this:
all_attributes = hashes.map {|hash| hash["attributes"] }
# => [ { "id" => "usdeur", "code" => 4 },
# { "id" => "eurgbp", "code" => 5 } ]
all_ids = all_attributes.map {|attrs| attrs["id"] }
# => [ "usdeur", "eurgbp" ]
Or just:
p hashes.map {|hash| hash["attributes"]["id"] }
# => [ "usdeur", "eurgbp" ]
JSON library what using Rails is very slowly...
I prefer to use:
gem 'oj'
from https://github.com/ohler55/oj
fast and simple! LET'S GO!

ruby hash check if value exists

Must be an easy question.. but I can't seem to find the answer.
I'm trying to check if a value exists for a specific key within hash.
hash = {{"name" => "John", "Loc" => "US", "fname" => "John Doe"},
{"name" => "Eve", "Loc" => "UK", "fname" => "John Eve"}}
Currently I am looping through hash, to check for if h["name"] = "John"...
I was looking to see if a .include or .has_value? type of approach is available. I read the documentation on hash and a book I have on hand but couldn't find it.
I thought something like if hash["name"].has_value?("John") be most useful than looping through hash. Thanks in advance for the help!
First of all our hash is not a valid hash. I suppose you want to have an array of hashes like this
array = [
{ "name" => "John", "Loc" => "US", "fname" => "John Doe" },
{ "name" => "Eve", "Loc" => "UK", "fname" => "John Eve" }
]
then you can do something like this:
array.select { |hash| hash['name'] == 'John' }
# => returns [{"name" => "John", "Loc" => "US", "fname" => "John Doe"}]
array.any? { |hash| hash['name'] == 'John' }
# => true

Get the value of a key of each hash inside an array

I have got an array of hashes, for example:
[{"id" => "1", "name" => "Name 1"},
{"id" => "2", "name" => "Name 2"},
{"id" => "3", "name" => "Name 3"}]
I would like to get the value of the key "name" for each hash, similar to this:
["Name 1", "Name 2", "Name 3"]
I looked around for quite a while but couldn't find the answer I was looking for.
It's simplest to use Enumerable#map for this purpose:
array = [{"id" => "1", "name" => "Name 1"}, {"id" => "2", "name" => "Name 2"}, {"id" => "3", "name" => "Name 3"}]
array.map { |hash| hash['name'] }
# => ["Name 1", "Name 2", "Name 3"]

Resources