Get value from Ruby hash - ruby

I want to use this Ruby code to get fixed values:
FIXED_COUNTRY_TO_PHONE = [
{ country: 'FI', customer_phone: '+4672345678' },
{ country: 'SE', customer_phone: '+4672311178' }
].freeze
I tries this: FIXED_COUNTRY_TO_PHONE[country] but I don't get the customer_phone value. How I can get the value?

Hash is within an array so use this
p FIXED_COUNTRY_TO_PHONE.map{|x| x[:country]}
output
["FI", "SE"]
If you want to take the first country then
p FIXED_COUNTRY_TO_PHONE.first[:country]
If you want to take the last country then
p FIXED_COUNTRY_TO_PHONE.last[:country]
Getting the country code according to country
p FIXED_COUNTRY_TO_PHONE.detect{|x| x[:country].eql?'FI'}[:customer_phone]

Related

Ruby: Hash w/ Arrays, Returning Associated Key If Value Is In Array

New to Ruby and have run out of ideas. I have an array of books that I would like to 1) Shelve 2) Find which shelf it is on 3) Remove it from the associated shelf if found. For brevity I have an array of 6 books. Each shelf contains 5 books.
library_catalog = [ "Book1", "Book2", "Book3", "Book4", "Book5", "Book6" ]
shelves = Hash.new(0)
catalog_slice = library_catalog.each_slice(5).to_a
count = 1
catalog_slice.each do | x |
shelves.merge!(count=>x)
count+=1
end
From this I know have a Hash w/ arrays as such
{1=>["Book1", "Book2", "Book3", "Book4", "Book5"], 2=>["Book6"]}
This is where I'm having trouble traversing the hash to find a match inside the array and return the key(shelf). If I have title = "Book1" and I am trying to match and return 1, how would I go about this?
I think this should work.
shelves.select { |k,v| v.include?("Book1")}.keys.first
selected the hashes that have a value equal to the title you are looking for (in this case "Book1")
get the keys for these hashes as an array
get the first entry in the array.
to remove the Book from the shelf try this:
key = shelves.select { |k,v| v.include?("Book1")}.keys.first
shelves[key].reject! { |b| b == "Book1" }
get a reference to the array and then reject the entry you want to remove

Keep id order as in query

I'm using elasticsearch to get a mapping of ids to some values, but it is crucial that I keep the order of the results in the order that the ids have.
Example:
def term_mapping(ids)
ids = ids.split(',')
self.search do |s|
s.filter :terms, id: ids
end
end
res = term_mapping("4,2,3,1")
The result collection should contain the objects with the ids in order 4,2,3,1...
Do you have any idea how I can achieve this?
If you need to use search you can sort ids before you send them to elasticsearch and retrive results sorted by id, or you can create a custom sort script that will return the position of the current document in the array of ids. However, a simpler and faster solution would be to simply use Multi-Get instead of search.
One option is to use the Multi GET API. If this doesn't work for you, another solution is to sort the results after you retrieve them from es. In python, this can be done this way:
doc_ids = ["123", "333", "456"] # We want to keep this order
order = {v: i for i, v in enumerate(doc_ids)}
es_results = [{"_id": "333"}, {"_id": "456"}, {"_id": "123"}]
results = sorted(es_results, key=lambda x: order[x['_id']])
# Results:
# [{'_id': '123'}, {'_id': '333'}, {'_id': '456'}]
May be this problem is resolved,, but someone will help with this answer
we can used the pinned_query for the ES. Do not need the loop for the sort the order
**qs = {
"size" => drug_ids.count,
"query" => {
"pinned" => {
"ids" => drug_ids,
"organic" => {
"terms": {
"id": drug_ids
}
}
}
}
}**
It will keep the sequence of the input as it

Set array elements (string) as variable name in Ruby

I have the following array, that I use to later write the header on an Excel file.
fields = ["fileName", "type", "id"]
And then I have the following code that reads values from an XML:
filename = xml.xpath('//path/filename').text
type = xml.xpath('//path/type').text
id = xml.xpath('//path/id').text
The I iterate the initial array (fields) in order to set the Excel cells to the values extracted in the previous step:
row = 2
c = 1
fields.each do |content|
ws.Cells(row,c).Value = content
c = c + 1
I'm trying to have the array's (fields) contents to variable names instead of strings in order to be able to reuse the head fields.
Can anyone recommend a way of making it possible?
This sounds like you need to use a Hash to associate field names to the values you extracted:
fields = {
"fileName" => xml.xpath('//path/filename').text,
"type" => xml.xpath('//path/type').text,
"id" => xml.xpath('//path/id').text
}
row=2
c=1
fields.each do |key,value|
ws.Cells(row,c).Value = value
c=c+1
end

Gruff Bar Graph Data in array,

I need a Bar Graph in Gruff with two Bars.
For two subjects, I loop through to get the values for activity and grade :
sub = ["English", "Maths"]
activity = []
grade = []
sub.each do |sub|
activity.push(sub["activity"].to_i)
grade.push(sub["grade"].to_i)
end
Now, I am using these values for my Bar Graph.
g = Gruff::Bar.new('500x250')
g.maximum_value = 100
g.minimum_value = 0
g.y_axis_increment = 15
g.data( "Activity", activity.inspect)
g.data( "Summative", grade.inspect)
g.labels = {0 => 'English', 1 => 'Language II'}
g.write('images/overall_score.png')
But, this throws an error " comparison of String with 0 failed". I need the data to be printed as
g.data( "Activity", [10,20])
puts activity.inspect prints the array as above ex: [10,20]
Looks like the values are treated as strings. What should I do to resolve this.
Any help is greatly appreciated.
Cheers!
Actually inspect method returns String. I think you should just pass your arrays to data method like this:
g.data("Activity", activity)
g.data("Summative", grade)

Using Ruby, how can I get the sum of a specific item out of an array of hashes?

I'm confused, I have #quote.quote_line_items and this is an array of items like this:
[{id: 85, part_number: "X67AC0M08", short_description: "X67 Threaded Caps M8, 50 pieces", list_price: "18.00", arg_cost: "12.15", long_description: "X67 Threaded Caps M8, 50 pieces", created_at: "2009-11-27 20:29:58", updated_at: "2009-11-27 20:29:58", quote_id: 1259353798}, {...}]
Consider if many items like this are in an array, how can I get, say, all of the list_price values summed up.
Is there a simple method to get the sum of all the list_price values by key?
Given the array = [itemA, ...], and each item has method list_price, then you can do that:
sum = array.map{|i|i.list_price}.reduce(:+)
or
sum = array.reduce(0) {|sum,item| sum + item.list_price }
If each item is hash, and you want to get values from :list_price, then try this:
sum = array.reduce(0) {|sum,item| sum + item[:list_price].to_f }
Note: edited after you corrected the example in question

Resources