merge every 3rd Hash in Array - ruby

Hi I can't find how to merge every 3 hashes of an array.
here is my array of hashes.
[
{:key1=>"v1"}, {:ky2 => "v2"}, {:key3 => "v3"},
{:key1=>"v4"}, {:ky2 => "v5"}, {:key3 => "v6"},
{:key1=>"v7"}, {:ky2 => "v8"}, {:key3 => "v9"},..
]
What I would need is to merge every 3 hashes to look like this :
[
{:key1=>"v1", :ky2 => "v2", :key3 => "v3"},
{:key1=>"v4", :ky2 => "v5", :key3 => "v6"},
{:key1=>"v7", :ky2 => "v8", :key3 => "v9"},..
]
Thank in advance for you help.

I'd do
hs = [
{:key1=>"v1"}, {:ky2 => "v2"}, {:key3 => "v3"},
{:key1=>"v4"}, {:ky2 => "v5"}, {:key3 => "v6"},
{:key1=>"v7"}, {:ky2 => "v8"}, {:key3 => "v9"}
]
hs.each_slice(3).map { |grouped_hs| grouped_hs.inject(:merge) }
# => [{:key1=>"v1", :ky2=>"v2", :key3=>"v3"},
# {:key1=>"v4", :ky2=>"v5", :key3=>"v6"},
# {:key1=>"v7", :ky2=>"v8", :key3=>"v9"}]

a.flat_map(&:to_a).each_slice(3).map(&:to_h)
#=> [{:key1=>"v1", :ky2=>"v2", :key3=>"v3"},
#=> {:key1=>"v4", :ky2=>"v5", :key3=>"v6"},
#=> {:key1=>"v7", :ky2=>"v8", :key3=>"v9"}]
Array#to_h was added in v2.1.

a = [
{ :key1=>'v1' }, { :ky2 => 'v2' }, { :key3 => 'v3' },
{ :key1=>'v4' }, { :ky2 => 'v5' }, { :key3 => 'v6' },
{ :key1=>'v7' }, { :ky2 => 'v8' }, { :key3 => 'v9' }
]
a.each_slice(3).map{ |e| e.inject(&:merge) }

Related

Pushing objects into a hash inside a loop

I'm trying to achieve the following JSON results:
{
"movie" =>
[{
"title": "Thor",
"year" : 2011,
},
{
"title": "Iron Man",
"year" : 2008,
}],
"tv" =>
[{
"title": "Parks and Recreation"
"year": 2009
},
{
"title": "Friends"
"year": 1994
}]
}
With JavaScript, I would loop through my results and do something like:
results['movie'].push(item);
results['tv'].push(item);
With Ruby code, the farthest I've gone is this:
#results = Hash.new
results['Search'].each do |r|
if r['Type'] == 'movie'
#results['movie'] << {
'title' => r['Title'],
'year' => r['Year']
}
elsif r['Type'] == 'series'
#results['tv'] << {
'title' => r['Title'],
'year' => r['Year']
}
end
end
What am I missing here?
I think you can get what you want by using Enumerable#each_with_object and assigning a default value to the hash.
def group_search_results(items)
results = Hash.new { |hash, key| hash[key] = [] }
items.each_with_object(results) do |item|
results[item['Type']] << {'title' => item['Title'], 'year' => item['Year']}
end
end
describe "search_results" do
it "groups into an object" do
items = [
{'Type' => 'movie', 'Title' => 'Thor', 'Year' => 2011},
{'Type' => 'movie', 'Title' => 'Iron Man', 'Year' => 2008},
{'Type' => 'series', 'Title' => 'Parks and Recreation', 'Year' => 2009},
{'Type' => 'series', 'Title' => 'Friends', 'Year' => 1994},
]
results = group_search_results(items)
expect(results).to eq({
'movie' => [
{'title' => 'Thor', 'year' => 2011},
{'title' => 'Iron Man', 'year' => 2008},
],
'series' => [
{'title' => 'Parks and Recreation', 'year' => 2009},
{'title' => 'Friends', 'year' => 1994},
],
})
end
end
I believe the problem has to do with the initialization of your hash. The movie and tv keys aren't currently an array. You can initialize your hash like this:
#results = { 'movie' => [], 'tv' => [] }
Here's how it looks with the rest of your code:
#results = { 'movie' => [], 'tv' => [] }
results['Search'].each do |r|
if r['Type'] == 'movie'
#results['movie'] << {
'title' => r['Title'],
'year' => r['Year']
}
elsif r['Type'] == 'series'
#results['tv'] << {
'title' => r['Title'],
'year' => r['Year']
}
end
end
results = {
search: {
movie: [
{ title: 'Thor', year: 2011 },
{ title: 'Iron Man', year: 2008 },
],
tv: [
{ title: 'Parks and Recreation', year: 2009 },
{ title: 'Friends', year: 1994 },
]
}
}
#results = Hash.new{|k, v| k[v] = []}
results[:search].each do |type, array|
#results[type].push(*array)
end
results[:search].each_with_object(Hash.new{|k, v| k[v] = []}) do |(type, array), hash|
hash[type].push(*array)
end

How to add OR condition in Elasticsearch ruby query?

In my use case, I would like to add an OR condition in Elasticsearch query. Here is my query,
query_body = {
'query' => {
'bool' => {
'must' => [{ 'range' => {'#timestamp' => { 'from' => stream_filters[:first_time].gmtime.strftime("%Y-%m-%dT%H:%M:%SZ"), 'to' => stream_filters[:second_time].gmtime.strftime("%Y-%m-%dT%H:%M:%SZ") } } }, {'term' => {"#timeout" => true} }, {'term' => {"#dest" => dest} }, {'term' => {"#source" => source} } ]
}
}, 'facets' => facets
}
I would like to add 'term' => {"#dest" => ' '} empty check for #dest along with 'term' => {"#dest" => dest}
I tried to add an or condition, But it is not working.
query_body = {
'query' => {
'bool' => {
'must' => [{ 'range' => {'#timestamp' => { 'from' => stream_filters[:first_time].gmtime.strftime("%Y-%m-%dT%H:%M:%SZ"), 'to' => stream_filters[:second_time].gmtime.strftime("%Y-%m-%dT%H:%M:%SZ") } } }, {'term' => {"#timeout" => true} }, {'term' => {"#source" => source} } ],
'filter' => {
'or' => [{
'term' => { "#dest" => dest }
'term' => { "#dest" => ' ' }
}]
}
}
}, 'facets' => facets
}
Could someone help me with this?
It seems like a syntax error in your filter clause. Please try with the correct syntax as below :
'filter' => {
'or' => [
{
'term' => { "#dest" => dest }
},
{
'term' => { "#dest" => ' ' }
}
]
}

Nested hash iteration: How to iterate a merge over an ( (array of hashes) within a hash )

I'm trying to do as the title says. Here is my code:
school.each { |x| school[:students][x].merge!(semester:"Summer") }
I think I pinpointed the problem to the "[x]" above. If I substitute an array position such as "[2]" it works fine. How can make the iteration work?
If the info above is not enough or you'd like to offer a better solution, please see the details below. Thanks!
The error message I get:
file.rb:31:in []': no implicit conversion of Array into Integer (TypeError)
from file.rb:31:inblock in '
from file.rb:31:in each'
from file.rb:31:in'
The nested hash below before alteration:
school = {
:name => "Happy Funtime School",
:location => "NYC",
:instructors => [
{:name=>"Blake", :subject=>"being awesome" },
{:name=>"Ashley", :subject=>"being better than blake"},
{:name=>"Jeff", :subject=>"karaoke"}
],
:students => [
{:name => "Marissa", :grade => "B"},
{:name=>"Billy", :grade => "F"},
{:name => "Frank", :grade => "A"},
{:name => "Sophie", :grade => "C"}
]
}
I'm trying to append :semester=>"Summer" to each of the last four hashes. Here is what I'm trying to go for:
# ...preceding code is the same. Changed code below...
:students => [
{:name => "Marissa", :grade => "B", :semester => "Summer"},
{:name=>"Billy", :grade => "F", :semester => "Summer"},
{:name => "Frank", :grade => "A", :semester => "Summer"},
{:name => "Sophie", :grade => "C", :semester => "Summer"}
]
}
Just iterate over the students:
school[:students].each { |student| student[:semester] = "Summer" }
Or, using merge:
school[:students].each { |student| student.merge!(semester: "Summer") }
The issue is that when you do array.each {|x| do something}, x actually refers to each element in the array.
For example, in the first iteration of the loop,
x = {:name => "Marissa", :grade => "B"}
So what you are really doing is trying to reference:
school[:student][{:name => "Marissa", :grade => "B"}]
Which will not work
What you could do instead is create a for loop to track the index.
for i in 0 ... school[:student].count
school[:students][i].merge!(semester:"Summer")
end
Edit: Stefan's solution is much better than mine, but I will leave this up to show where you went wrong.
I would do as below using Hash#store :
require 'awesome_print'
school = {
:name => "Happy Funtime School",
:location => "NYC",
:instructors => [
{
:name => "Blake",
:subject => "being awesome"
},
{
:name => "Ashley",
:subject => "being better than blake"
},
{
:name => "Jeff",
:subject => "karaoke"
}
],
:students => [
{
:name => "Marissa",
:grade => "B"
},
{
:name => "Billy",
:grade => "F"
},
{
:name => "Frank",
:grade => "A"
},
{
:name => "Sophie",
:grade => "C"
}
]
}
school[:students].each{|h| h.store(:semester ,"Summer")}
ap school,:index => false,:indent => 10
output
{
:name => "Happy Funtime School",
:location => "NYC",
:instructors => [
{
:name => "Blake",
:subject => "being awesome"
},
{
:name => "Ashley",
:subject => "being better than blake"
},
{
:name => "Jeff",
:subject => "karaoke"
}
],
:students => [
{
:name => "Marissa",
:grade => "B",
:semester => "Summer"
},
{
:name => "Billy",
:grade => "F",
:semester => "Summer"
},
{
:name => "Frank",
:grade => "A",
:semester => "Summer"
},
{
:name => "Sophie",
:grade => "C",
:semester => "Summer"
}
]
}

How can i update the ids field with this rethinkdb document structure?

Having trouble trying to update the ids field in the document structure:
[
[0] {
"rank" => nil,
"profile_id" => 3,
"daily_providers" => [
[0] {
"relationships" => [
[0] {
"relationship_type" => "friend",
"count" => 0
},
[1] {
"relationship_type" => "acquaintance",
"ids" => [],
"count" => 0
}
],
"countries" => [
[0] {
"country_name" => "United States",
"count" => 0
},
[1] {
"country_name" => "Great Britain",
"count" => 0
}
],
"provider_name" => "foo",
"date" => 20130912
},
[1] {
"provider_name" => "bar"
}
]
}
]
In JavaScript, you can do
r.db('test').table('test').get(3).update(function(doc) {
return {daily_providers: doc("daily_providers").changeAt(
0,
doc("daily_providers").nth(0).merge({
relationships: doc("daily_providers").nth(0)("relationships").changeAt(
1,
doc("daily_providers").nth(0)("relationships").nth(1).merge({
ids: [1]
})
)
})
)}
})
Which becomes in Ruby
r.db('test').table('test').get(3).update{ |doc|
{"daily_providers" => doc["daily_providers"].changeAt(
0,
doc["daily_providers"][0].merge({
"relationships" => doc["daily_providers"][0]["relationships"].changeAt(
1,
doc["daily_providers"][0]["relationships"][1].merge({
ids => [1]
})
)
})
)}
}
You should probably have another table for the daily providers and do joins.
That would make things way more simpler.

What's the best way to replace a string inside a string in ruby?

I have a bunch of these:
'link' => "http://twitter.com/home?status=Check out "{title}" {url}",
And Want to replace the {title} and {url} bits.
I'm currently doing this with gsub:
l.gsub! "{url}", URI::encode(#opts[:url])
l.gsub! "{title}", URI::encode(#opts[:title])
But I have the feeling there's a much better way to do this than with gsub...
#
This is an edit / addition to clarify:
class SocialBookmarkMaker
require 'open-uri'
attr_accessor :opts
def initialize(opts)
#opts = ##default_opts.merge opts
end
##default_opts = {
:icon_folder => "/images/icons/social_aquatic/24 X 24",
:sites => ['facebook', 'twitter', 'delicious', 'digg', 'stumbleupon', 'reddit', 'technorati', ],
:ext => 'png',
:url => 'not provided',
:title => 'not provided',
}
##bookmarks = {
'yahoo' => {
'name' => 'Yahoo! My Web',
'link' => 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u={url}&t={title}',
},
'google' => {
'name' => 'Google Bookmarks',
'link' => 'http://www.google.com/bookmarks/mark?op=edit&bkmk={url}&title={title}',
},
'windows' => {
'name' => 'Windows Live',
'link' => 'https://favorites.live.com/quickadd.aspx?url={url}&title={title}',
},
'facebook' => {
'name' => 'Facebook',
'link' => 'http://www.facebook.com/sharer.php?u={url}&t={title}',
},
'digg' => {
'name' => 'Digg',
'link' => 'http://digg.com/submit?phase=2&url={url}&title={title}',
},
'ask' => {
'name' => 'Ask',
'link' => 'http://myjeeves.ask.com/mysearch/BookmarkIt?v=1.2&t=webpages&url={url}&title={title}',
},
'technorati' => {
'name' => 'Technorati',
'link' => 'http://www.technorati.com/faves?add={url}',
},
'delicious' => {
'name' => 'del.icio.us',
'link' => 'http://del.icio.us/post?url={url}&title={title}',
},
'stumbleupon' => {
'name' => 'StumbleUpon',
'link' => 'http://www.stumbleupon.com/submit?url={url}&title={title}',
},
'squidoo' => {
'name' => 'Squidoo',
'link' => 'http://www.squidoo.com/lensmaster/bookmark?{url}'
},
'netscape' => {
'name' => 'Netscape',
'link' => 'http://www.netscape.com/submit/?U={url}&T={title}',
},
'slashdot' => {
'name' => 'Slashdot',
'link' => 'http://slashdot.org/bookmark.pl?url={url}&title={title}',
},
'reddit' => {
'name' => 'reddit',
'link' => 'http://reddit.com/submit?url={url}&title={title}',
},
'furl' => {
'name' => 'Furl',
'link' => 'http://furl.net/storeIt.jsp?u={url}&t={title}',
},
'blinklist' => {
'name' => 'BlinkList',
'link' => 'http://blinklist.com/index.php?Action=Blink/addblink.php&Url={url}&Title={title}',
},
'dzone' => {
'name' => 'dzone',
'link' => 'http://www.dzone.com/links/add.html?url={url}&title={title}',
},
'swik' => {
'name' => 'SWiK',
'link' => 'http://stories.swik.net/?submitUrl&url={url}'
},
'shoutwire' => {
'name' => 'Shoutwrie',
'link' => 'http://www.shoutwire.com/?p=submit&&link={url}',
},
'blinkbits' => {
'name' => 'Blinkbits',
'link' => 'http://www.blinkbits.com/bookmarklets/save.php?v=1&source_url={url}',
},
'spurl' => {
'name' => 'Spurl',
'link' => 'http://www.spurl.net/spurl.php?url={url}&title={title}',
},
'diigo' => {
'name' => 'Diigo',
'link' => 'http://www.diigo.com/post?url={url}&title={title}',
},
'tailrank' => {
'name' => 'Tailrank',
'link' => 'http://tailrank.com/share/?link_href={url}&title={title}',
},
'rawsugar' => {
'name' => 'Rawsugar',
'link' => 'http://www.rawsugar.com/tagger/?turl={url}&tttl={title}&editorInitialized=1',
},
'twitter' => {
'name' => 'Twitter',
'link' => "http://twitter.com/home?status=Check out "{title}" {url}",
},
}
def self.bookmarks
##bookmarks
end
def icon_loc(site)
"http://common-resources.---.net.s3.amazonaws.com#{#opts[:icon_folder]}/#{site}.#{#opts[:ext]}"
end
def link_url(site)
l = SocialBookmarkMaker.bookmarks[site]['link']
l.gsub! "{url}", URI::encode(#opts[:url])
l.gsub! "{title}", URI::encode(#opts[:title])
l
end
end
shared/social_bookmarks/standard.html.haml
- opts ||= {}
- opts.merge! :url => request.url
- opts.merge! :title => "---.net: #{#layout[:social_bookmark_title] || #layout[:title] || default_view_title}"
- b = SocialBookmarkMaker.new opts
- b.opts[:sites].each do |site|
= link_to(image_tag( b.icon_loc(site) ), b.link_url(site), :title => "Share on #{SocialBookmarkMaker.bookmarks[site]['name']}")
I then call this like this in my rails layout:
render :partial => "shared/social_bookmarks/standard", :locals => { :opts => {:icon_folder => "/images/icons/social_aquatic/48 X 48" }}
Either you change your string to look like
"http://twitter.com/home?status=Check out "%{title}" %{url}"
and then use printf with a Hash
s = "http://twitter.com/home?status=Check out "%{title}" %{url}"
# you can of course use #opts as the Hash here.
s = s % {:title => "abc", :url => "def"} # => "http://twitter.com/home?status=Check out "abc" def"
and accept that it only works with Ruby 1.9.2 and upwards, or you continue using gsub but using the block syntax to condense it:
s.gsub!(/\{(.+?)\}/) do |m|
#opts[$1.to_sym]
end
You can just embed the variables directly in the string
'link' => "http://twitter.com/home?status=Check out "#{title}" #{url}"

Resources