Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
{"headends"=>
[{"headend"=>
{"id"=>341766992,
"headend_name"=>"Comcast Burlingame Digital",
"dma_code"=>"807",
"dma_rank"=>6,
"system_name"=>"Comcast",
"headend_city"=>"Burlingame",
"headend_state"=>"CA",
"headend_time_zone"=>"PT",
"dma_name"=>"SAN FRANCISCO-OAK-SAN JOSE",
"channel_device"=>"X",
"country"=>"",
"service_type"=>"CA"},
"mso"=>{"id"=>341775346, "mso_name"=>"Comcast Cable Communications"},
"postal_code"=>"94010",
"device_id"=>"5b9a5042"}],
"services"=>
["amazon",
"directv",
"hbogo",
"hulu",
"itunes",
"itunes",
"netflixusa",
"showtime",
"vudu",
"youtube"],
"postal_code"=>nil,
"apps"=>
["cf528ea9",
"ea0f81d1",
"2ba2dc0e",
"50107ad3",
"3c103fa4",
"692bea67",
"557e96d5",
"b2db5e2a",
"0247ee5a",
"f0ad77dc",
"b24c00b1"]}
This is my hash, how can i extract values like "id"=>341766992, "postal_code"=>"94010"
For things that are hashes, e.g. {"foo"=>"bar", "baz"=>"blah"}, index into them with the key, e.g. myhash["foo"] # "baz".
For things that are arrays, e.g. ["hello", "world"], use their 0-based numeric indices, e.g. myarray[1] # "world".
Put those things together to dig through your structure, which I pretty-printed in an edit to your question:
data = {"headends"=>[{"headend"=>{"id"=>341766992, "headend_name"=>"Comcast Burlingame Digital", "dma_code"=>"807", "dma_rank"=>6, "system_name"=>"Comcast", "headend_city"=>"Burlingame", "headend_state"=>"CA", "headend_time_zone"=>"PT", "dma_name"=>"SAN FRANCISCO-OAK-SAN JOSE", "channel_device"=>"X", "country"=>"", "service_type"=>"CA"}, "mso"=>{"id"=>341775346, "mso_name"=>"Comcast Cable Communications"}, "postal_code"=>"94010", "device_id"=>"5b9a5042"}], "services"=>["amazon", "directv", "hbogo", "hulu", "itunes", "itunes", "netflixusa", "showtime", "vudu", "youtube"], "postal_code"=>nil, "apps"=>["cf528ea9", "ea0f81d1", "2ba2dc0e", "50107ad3", "3c103fa4", "692bea67", "557e96d5", "b2db5e2a", "0247ee5a", "f0ad77dc", "b24c00b1"]}
puts data["headends"][0]["headend"]["id"]
puts data["headends"][0]["postal_code"]
# Output:
# 341766992
# 94010
Prior to Ruby 2.3:
input['headends'].map do |e|
[
e['postal_code'],
*e['headend'].values_at(*%w|id|),
*e['mso'].values_at(*%w|id|),
]
end
2.3+
input['headends'].map do |e|
[%w|postal_code|, %w|headend id|, %w|mso id|].map do |key|
e.dig(*key)
end
end
Your question has been answered but I'm posting this to better show the format of the hash and also to point out that the example given could be drastically reduced in size and still make the same point.
h = { "headends"=>
[
{ "headend"=> {
"id" =>341766992,
"channel_device"=>"X",
"service_type" =>"CA"
},
"mso"=> {
"id" =>341775346,
"mso_name"=>"Comcast Cable Communications"
},
"postal_code"=>"94010",
"device_id" =>"5b9a5042"
}
]
}
h["headends"][0]["headend"]["id"] #=> 341766992
h["headends"][0]["postal_code"] #=> "94010"
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
I have a hash ref with values being an array ref. I would like to sort the hash using multiple values. For example:
{ 'ID' => ['Age', 'Name', 'Start-Date'] }
I would like to sort by: 1) Age; then-by by 2) Start-Date (if Ages are equal). For example:
#!/usr/bin/env perl
use strict;
use warnings;
my $r = {
'QX' => ['17','Jack','2022-05-31'],
'ZE' => ['19','Jill','2022-05-31'],
'RW' => ['17','Aida','2022-08-23'],
'FX' => ['19','Bill','2022-05-23'],
'IR' => ['16','Dave','2022-04-01']
};
for my $key (sort {$r->{$a}-[0] <=> $r->{$b}-[0] or $r->{$a}-[2] cmp $r->{$b}-[2]} keys %{$r}) {
say STDERR "$key: $r->{$key}->[0] : $r->{$key}->[2] : $r->{$key}->[1]";
}
The code above, however, yields incosistent reults.
My expected output (sort by Age followed-by Start-Date) would be:
IR: 16 : 2022-04-01 : Dave
QX: 17 : 2022-05-31 : Jack
RW: 17 : 2022-08-23 : Aida
FX: 19 : 2022-05-23 : Bill
ZE: 19 : 2022-05-31 : Jill
$r->{$a}-[0]
should be
$r->{$a}->[0]
or just
$r->{$a}[0] # Arrow optional between indexes.
You could also use
use Sort::Key::Multi qw( uskeysort );
uskeysort { $r->{ $_ }->#[ 0, 2 ] } keys %$r
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi I want to create A YML file and load them as instance variables instead. How can I do that.
yml_File.yml File ::
default:
browserversion: 43
dev:
browser_02: iexplore
qa_01:
browser_default: chrome
qa_02:
browser_default: safari
Check the below Code::
p yml_File = YAML.load_file(File.dirname(__FILE__).gsub('/', '\\') + '\\Profiles.yml')
yml_File.each_key {|key_Value|
va = yml_File[key_Value].to_s
var_name = "##{key_Value}" # the '#' is required
self.instance_variable_set(var_name, va)
p "Name of Instance variable '#{key_Value}' is :: " + var_name.to_s + ' - And Key value is : ' + eval("##{key_Value}")
}
p #dev
p #qa_01
p #qa_02
Note - Ruby 1.9+ atleast
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have quite the annoying bug right now, whenever I run this code
function player.detect()
for j = #bullet, 1, -1 do
if CheckCollision(bullet[j].x, bullet[j].y, bullet.w, bullet.h, enemy.x, enemy.y, enemy.w, enemy.h) then
table.remove(bullet, j)
end
end
end
for j = #enemy, 1, -1 do
if CheckCollision(bullet.x, bullet.y, bullet.w, bullet.h, enemy[j].x, enemy[j].y, enemy.w, enemy.h) then
table.remove(enemy, j)
end
end
end
end
It says: Error: Syntax error: player.lua:118: '' expected near 'end'
Yes, this is player.lua, and yes the code displayed is line 104-119. Thanks for reading! Anything helps!
You have too many ends!
function player.detect()
for j = #bullet, 1, -1 do
if CheckCollision(bullet[j].x, bullet[j].y, bullet.w, bullet.h, enemy.x, enemy.y, enemy.w, enemy.h) then
table.remove(bullet, j)
end
end
for j = #enemy, 1, -1 do
if CheckCollision(bullet.x, bullet.y, bullet.w, bullet.h, enemy[j].x, enemy[j].y, enemy.w, enemy.h) then
table.remove(enemy, j)
end
end
end
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to convert this:
[{"day"=>"2014-02-01", "users"=>1234},
{"day"=>"2014-02-02", "users"=>2234},
{"day"=>"2014-02-03", "users"=>3234},
{"day"=>"2014-02-04", "users"=>4234}]
into this:
[{:x=>1, y:=>1234},
{:x=>2, y:=>2234},
{:x=>3, y:=>3234},
{:x=>4, y:=>4234}]
a = [{"day"=>"2014-02-01", "users"=>1234}, {"day"=>"2014-02-02", "users"=>2234}, {"day"=>"2014-02-03", "users"=>3234}, {"day"=>"2014-02-04", "users"=>4234}]
a.map.with_index(1) { |h,i| { :x => i, :y => h['users'] } }
# => [{:x=>1, :y=>1234}, {:x=>2, :y=>2234}, {:x=>3, :y=>3234}, {:x=>4, :y=>4234}]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have a method from a long script that creates a hash from genetic sequences, however it is really messy and thus I was wondering whether there was a way to put it more elegantly.
Here is a sample of the script (i.e. it contains an example)...
def make_hash(motif)
main_hash = Hash.new
id = ">isotig00009_f2_3 ~: S.P. Cleavage Site: 22:23 - S.P. D-value: 0.532"
seq = "MLKCFSIIMGLILLLEIGGGCA~IYFYRAQIQAQFQKSLTDVTITDYRENADFQDLIDALQSGLSCCGVNSYEDWDNNIYFNCSGPANNPEALWCAFLLLYTGSSKRSSQHPVRLWSSFPRTTKYFPHKDLHHWLCGYVYNVD"
id_hash = Hash[[[:id_start, :id_end], id.split("~").map(&:strip)].transpose]
seq_hash = Hash[[[:signalp, :seq_end], seq.split("~").map(&:strip)].transpose]
signalp = seq_hash[:signalp]
new_seq_end = seq_hash[:seq_end].gsub(/#{motif}/, '<span class="motif">\0</span>')
new_seq_hash = Hash[:signalp => signalp, :new_seq_end => new_seq_end ]
main_hash[id_hash] = [new_seq_hash]
return main_hash
end
motif = "VT|QAQ|F.D"
main_hash = make_hash(motif)
main_hash.each do |id_hash, seq_hash|
puts id_hash[:id_start]
puts id_hash[:id_end]
puts seq_hash[0][:signalp]
puts seq_hash[0][:new_seq_end]
end
So Is there a more elegant way to write the make_hash method...
Many Thanks
I haven't tested this, but I think this simplification will work:
def make_hash(motif)
id = ">isotig00009_f2_3 ~: S.P. Cleavage Site: 22:23 - S.P. D-value: 0.532"
seq = "MLKCFSIIMGLILLLEIGGGCA~IYFYRAQIQAQFQKSLTDVTITDYRENADFQDLIDALQSGLSCCGVNSYEDWDNNIYFNCSGPANNPEALWCAFLLLYTGSSKRSSQHPVRLWSSFPRTTKYFPHKDLHHWLCGYVYNVD"
id_hash = Hash[[[:id_start, :id_end], id.split("~").map(&:strip)].transpose]
f, s = seq.split("~").map(&:strip)
s.gsub!(/#{motif}/, '<span class="motif">\0</span>')
new_seq_hash = Hash[Hash[:signalp, f], Hash[:new_seq_end, s]]
Hash[id_hash, new_seq_hash]
end
If (as it appears) id and seq both have constant values, you might consider breaking them apart manually, rather than with id.split("~").map(&:strip); i.e.,
id1 = ">isotig00009_f2_3
id2 = ": S.P. Cleavage Site: 22:23 - S.P. D-value: 0.532"
seq1 = "MLKCFSIIMGLILLLEIGGGCA"
seq2 = "IYFYRAQIQAQFQKSLTDVTITDYRENADFQDLIDALQSGLSCCGVNSYEDWDNNIYFNCSGPANNPEALWCAFLLLYTGSSKRSSQHPVRLWSSFPRTTKYFPHKDLHHWLCGYVYNVD"
If there were a need to make seq2 more readable, we could use the "line continuation" character, \ (which even works within strings) like this:
seq2 = "IYFYRAQIQAQFQKSLTDVTITDYRENADFQDLIDALQSGLSCCGVNSYEDWDNNIYFNC"\
"SGPANNPEALWCAFLLLYTGSSKRSSQHPVRLWSSFPRTTKYFPHKDLHHWLCGYVYNVD"
or this:
seq2 = "IYFYRAQIQAQFQKSLTDVTITDYRENADFQDLIDALQSGLSCCGVNSYEDWDNNIYFNC\
SGPANNPEALWCAFLLLYTGSSKRSSQHPVRLWSSFPRTTKYFPHKDLHHWLCGYVYNVD"
If you preferred, you could make 'id' and 'seq' constants ('ID' and 'SEQ', say) and move them outside the method definition. Not surprisingly, line continuation also works for constant strings.