Finding hashes with items from the array using ruby - ruby

Sorry for missunderstanding for my fault I didn't check class of item...
I have an array:
array = [link1, link2, link3, link4, etc]
and array_of_hashes with two items: names and links
hash = [ :names, :links ] e.g.
array_of_hashes = [{ :names => name1, :links => link1}, {:names = name2, :links => link2}, ... ]
I want to do something with each pair of items from array_of_hashes which includes links from the array.
UPD: Revised data... sorry for missunderstanding.

It was a bit vague of a question but here is a shot at it.
you will need to reorder what you're trying to access from the hash, unless :name is required.
arr = ["link0", "link1",..."linkN"]
hsh = { "link0", item0, "link1", item1, "link1", item2,..."linkN", itemN}
hsh.each_pair | link, item |
do_something_foo(item) if arr.include?(link) # do_something_foo is a predefined function
end
jagga99 wrote
I want to do something with each item from hash which contain links from the array. Thanks a lot for your help.
If the [:name, :link] is the require pair, then you would need to identify which part is the item to do something with: the name or the link.

Enumerate the array of hashes and search the link array.
array = [:link1, :link2, :link3]
array_of_hashes = [{ :names => :name1, :links => :no_link}, {:names => :name2, :links => :link2}]
array_of_hashes.each do |hash|
if array.any? {|s| s==hash[:links]}
puts "Do something with #{hash[:names].to_s}"
end
end

Related

Dashing reading out of 2 different CSV's

Hello everyone I'm currently trying to get my Dashboard working properly, however I cannot figure out a way to get the values into something my List Widget can read.
begin
id = 1
names.each do |item|
label = names[id][0] #names = names.csv path
value = host_status[id]['status'] #host_status = host_status.csv path
items = { label: label, value: value }
id += 1
end
rescue
end
send_event('hosts', { items: items })
So what this script should do is :
write the host_status.csv with the values it gets from the status.cgi (working)
iterate through both the host_status.csv and names.csv getting values from both of them
output should be something like this (label comes from names.csv, value from host_status.csv) =>
{label: "localhost", value: "UP"}, {label: "USV", value: "UP"}
The list widget needs something like an Array in a Hash with the keys label and value as far as I can tell, however my script doesnt return anything is there something like a push method for hashes?
I'm assuming here that names is an array of arrays [['foo'], ['bar']]
and that host_status is an array of objects [{'status' => 'foo'}, {'status' => 'bar'}]
you should just be able to do
names = [['foo'], ['bar']]
host_status = [{'status' => 'foo'}, {'status' => 'bar'}]
labels = names.map(&:first) # ['foo', 'bar']
values = host_status.map {|s| s['status'] } # ['foo', 'bar']
# zip zips together two arrays [['foo', 'foo'], ['bar', 'bar']]
# inject iterates over the array and returns a new data structure
items = labels.zip(values).inject([]) do |memo, (k,v)|
memo.push({label: k, value:v})
memo
end
You should just be able to run that code sample in an irb session.
Enumerable#map:http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map
Enumerable#zip: http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-zip
Enumerable#inject: http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-inject

I can't find a way to create a simple multidimensional array or hash in Ruby

You Ruby pros will laugh but I'm having such a hard time with this. I've searched and searched and tried a lot of different things but nothing seems right. I guess I'm just used to dealing with arrays in js and php. Here is what I want to do; consider this pseudo code:
i = 0
foreach (items as item) {
myarray[i]['title'] = item['title']
myarray[i]['desc'] = item['desc']
i++
}
Right, so then I can loop through myarray or access 'title' and 'desc' by the index (i). Simplest thing in the world. I've found a few ways to make it work in Ruby but they've all been really messy or confusing. I want to know the right way to do it, and the cleanest.
Unless you are actually updating my_array (which implies that there is probably a better way to do this), you probably want map instead:
items = [
{'title' => 't1', 'desc' => 'd1', 'other' => 'o1'},
{'title' => 't2', 'desc' => 'd2', 'other' => 'o2'},
{'title' => 't3', 'desc' => 'd3', 'other' => 'o3'},
]
my_array = items.map do |item|
{'title' => item['title'], 'desc' => item['desc'] }
end
items # => [{"title"=>"t1", "desc"=>"d1", "other"=>"o1"}, {"title"=>"t2", "desc"=>"d2", "other"=>"o2"}, {"title"=>"t3", "desc"=>"d3", "other"=>"o3"}]
my_array # => [{"title"=>"t1", "desc"=>"d1"}, {"title"=>"t2", "desc"=>"d2"}, {"title"=>"t3", "desc"=>"d3"}]
I'm not quite sure why you are trying to do this, as it seems like items is already an array with hashes inside it, and in my code below, myarray is exactly the same as items.
Try using each_with_index instead of a foreach loop:
items.each_with_index do |item, index|
myarray[index] = item
end
If you have extra attributes in each item, such as a id or something, then you would want to remove those extra attributes before you add the item to myarray.
titles = ["t1", "t2", "t3"]
descs = ["d1", "d2", "d3"]
h= Hash.new
titles.each.with_index{ |v,i| h[i] = {title: "#{v}" } }
puts h[0][:title] #=> t1
puts h #=> {0=>{:title=>"t1"}, 1=>{:title=>"t2"}...}
descs.each.with_index{ |v,i| h[i] = h[i].merge( {desc: "#{v}" } ) }
puts h[0][:desc] #=> d1
puts h #=> {0=>{:title=>"t1", :desc=>"d1"}, 1=>...

Iterate through hashed hashes in ruby

I am a beginner and am looking for a method to iterate through a hash containing hashed values. E.g. I only want to print a list of all values of inner hash-elements of the key named "label". My array is looking like this:
ary = Hash.new
ary[:item_1] = Hash[ :label => "label_1" ]
ary[:item_2] = Hash[ :label => "label_2" ]
ary[:item_3] = Hash[ :label => "label_3" ]
Now I want to iterate through all elements of the outer hash and try this:
ary.keys.each { |item| puts ary[:item] }
or this:
ary.keys.each { |item[:label]| puts ary[:item] }
Unfortunately both do not work. But if I try this - quite crazy feeling - detour, I get the result, which is I want to:
ary.keys.each { |item|
evalstr = "ary[:" + item.to_s + "][:label]"
puts eval(evalstr)
}
This yields the result:
label_1
label_2
label_3
I am absolutely sure that there must exist be a better method, but I have no idea how to find this method.
Thanks very much for your hints!
You can iterate through all values of an hash using each_value; or, you can iterate trough all key/value pairs of an hash using each, which will yield two variables, key and value.
If you want to print a single value for each hash value of the outer hash, you should go for something like this:
ary.each_value { |x| puts x[:label] }
Here's a more complex example that shows how each works:
ary.each { |key, value| puts "the value for :label for #{key} is #{value[:label]}" }
ary = Hash.new
ary[:item_1] = Hash[ :label => "label_1" ]
ary[:item_2] = Hash[ :label => "label_2" ]
ary[:item_3] = Hash[ :label => "label_3" ]
ary.flat_map{|_,v| v.values}
#=>["label_1", "label_2", "label_3"]
See Hash methods
> ary = Hash.new
> ary[:item_1] = Hash[ :label => "label_1" ]
> ary[:item_2] = Hash[ :label => "label_2" ]
> ary[:item_3] = Hash[ :label => "label_3" ]
> ary.values.each {|v| puts v[:label]}
label_1
label_2
label_3

Creating array of hashes in ruby

I want to create an array of hashes in ruby as:
arr[0]
"name": abc
"mobile_num" :9898989898
"email" :abc#xyz.com
arr[1]
"name": xyz
"mobile_num" :9698989898
"email" :abcd#xyz.com
I have seen hash and array documentation. In all I found, I have to do something
like
c = {}
c["name"] = "abc"
c["mobile_num"] = 9898989898
c["email"] = "abc#xyz.com"
arr << c
Iterating as in above statements in loop allows me to fill arr. I actually rowofrows with one row like ["abc",9898989898,"abc#xyz.com"]. Is there any better way to do this?
Assuming what you mean by "rowofrows" is an array of arrays, heres a solution to what I think you're trying to accomplish:
array_of_arrays = [["abc",9898989898,"abc#xyz.com"], ["def",9898989898,"def#xyz.com"]]
array_of_hashes = []
array_of_arrays.each { |record| array_of_hashes << {'name' => record[0], 'number' => record[1].to_i, 'email' => record[2]} }
p array_of_hashes
Will output your array of hashes:
[{"name"=>"abc", "number"=>9898989898, "email"=>"abc#xyz.com"}, {"name"=>"def", "number"=>9898989898, "email"=>"def#xyz.com"}]
you can first define the array as
array = []
then you can define the hashes one by one as following and push them in the array.
hash1 = {:name => "mark" ,:age => 25}
and then do
array.push(hash1)
this will insert the hash into the array . Similarly you can push more hashes to create an array of hashes.
You could also do it directly within the push method like this:
First define your array:
#shopping_list_items = []
And add a new item to your list:
#shopping_list_items.push(description: "Apples", amount: 3)
Which will give you something like this:
=> [{:description=>"Apples", :amount=>3}]

hash assignment when (key => value) are stored in an array? (ruby)

I have hash (#post) of hashes where I want to keep the order of the hash's keys in the array (#post_csv_order) and also want to keep the relationship key => value in the array.
I don't know the final number of both #post hashes and key => value elements in the array.
I don't know how to assign the hash in a loop for all elements in the array. One by one #post_csv_order[0][0] => #post_csv_order[0][1] works nicely.
# require 'rubygems'
require 'pp'
#post = {}
forum_id = 123 #only sample values.... to make this sample script work
post_title = "Test post"
#post_csv_order = [
["ForumID" , forum_id],
["Post title", post_title]
]
if #post[forum_id] == nil
#post[forum_id] = {
#post_csv_order[0][0] => #post_csv_order[0][1],
#post_csv_order[1][0] => #post_csv_order[1][1]
##post_csv_order.map {|element| element[0] => element[1]}
##post_csv_order.each_index {|index| #post_csv_order[index][0] => #post_csv_order[index][1] }
}
end
pp #post
desired hash assignment should be like that
{123=>{"Post title"=>"Test post", "ForumID"=>123}}
The best way is to use to_h:
[ [:foo,1],[:bar,2],[:baz,3] ].to_h #=> {:foo => 1, :bar => 2, :baz => 3}
Note: This was introduced in Ruby 2.1.0. For older Ruby, you can use my backports gem and require 'backports/2.1.0/array/to_h', or else use Hash[]:
array = [[:foo,1],[:bar,2],[:baz,3]]
# then
Hash[ array ] #= > {:foo => 1, :bar => 2, :baz => 3}
This is available in Ruby 1.8.7 and later. If you are still using Ruby 1.8.6 you could require "backports/1.8.7/hash/constructor", but you might as well use the to_h backport.
I am not sure I fully understand your question but I guess you want to convert a 2d array in a hash.
So suppose you have an array such as:
array = [[:foo,1],[:bar,2],[:baz,3]]
You can build an hash with:
hash = array.inject({}) {|h,e| h[e[0]] = e[1]; h}
# => {:foo=>1, :bar=>2, :baz=>3}
And you can retrieve the keys in correct order with:
keys = array.inject([]) {|a,e| a << e[0] }
=> [:foo, :bar, :baz]
Is it what you were looking for ?
Answers summary
working code #1
#post[forum_id] = #post_csv_order.inject({}) {|h,e| h[e[0]] = e[1]; h}
working code #2
#post[forum_id] = Hash[*#post_csv_order.flatten]
working code #3
#post[forum_id] ||= Hash[ #post_csv_order ] #requires 'require "backports"'

Resources