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 have this array of arrays:
[["abc", "123"], ["cde", "456"], ["cde", "674"]]
And I want this array of arrays arranged in this way:
{ "name": "test", "children": [ {"name": "abc", "children": [ {"name": "123"} ]}, {"name": "cde", "children": [ { "name": "456"},{"name": "674"} ]}]}
How can I make this transformation in ruby language?
Thanks in advance.
Try this
require 'json'
src_arr= [["abc", "123"], ["cde", "456"], ["cde", "674"]]
tmp = {} # to collect all common node first
src_arr.each do |arr|
if node = tmp[arr.first] # check if node exists
node['children'] << {'name' => arr.last} # append of exists
else
# add node if does not exists
tmp[arr.first] = {'name' => arr.first,'children' => [{'name' => arr.last}]}
end
end
tree = {'name' => 'test','children' => tmp.values}
puts tree
#=> {"name"=>"test", "children"=>[{"name"=>"abc", "children"=>[{"name"=>"123"}]}, {"name"=>"cde", "children"=>[{"name"=>"456"}, {"name"=>"674"}]}]}
puts JSON.generate(tree)
#=> {"name":"test","children":[{"name":"abc","children":[{"name":"123"}]},{"name":"cde","children":[{"name":"456"},{"name":"674"}]}]}
Related
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 have complex hash which looks like this
#hash = {1=>[], 2=>[], 3=>[], 4=>[], 5=>[], 6=>[], 7=>[], 8=>[], 9=>[], 10=>[], 11=>[], 12=>[[{"value"=>1.58, "title"=>"sun", "quantity" => 2}], [{"value"=>1.99, "title"=>"sophia", "quantity" => 5}], [{"value"=>6.30, "title"=>"roam", "quantity" => 15}], [{"value"=>3.981, "title"=>"jia, "quantity" => 4"}], 13 => [], 14 => [], 15 => []}
now I want to extract highest value along with associated title and quantity. index would 15 all the time.
for example the output should be
#hash = { value => 6.30, title => "roam", quantity => 15 }
I was searhcing some found this but did not make it work
reference link Ref
help appreciated thanks
If you're not interested in the element's index, you could flatten the values and find the maximum one:
#hash = {
1=>[], 2=>[], 3=>[], 4=>[], 5=>[], 6=>[], 7=>[], 8=>[], 9=>[],
10=>[], 11=>[], 12=>[
[{"value"=>1.58, "title"=>"sun", "quantity" => 2}],
[{"value"=>1.99, "title"=>"sophia", "quantity" => 5}],
[{"value"=>6.30, "title"=>"roam", "quantity" => 15}],
[{"value"=>3.981, "title"=>"jia", "quantity" => "4"}]
],
13 => [], 14 => [], 15 => []
}
#hash.values.flatten.max_by { |h| h["value"] }
#=> {"value"=>6.3, "title"=>"roam", "quantity"=>15}
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'm trying to use a Regular Expression to find all sub strings in word. It is finding some but not all. On such example is 'an' in the word 'banana'.
def substrings str
pattern = '.'
subs = []
while pattern.length < str.length do
subs << str.scan(/#{pattern}/)
pattern << '.'
end
subs.flatten
end
puts substrings("banana").sort_by{ |s| "banana".index(/#{s}/)}
Regular expression matches will never overlap. If you ask for /../, you will get ["ba", "na", "na"]. You will not get ["ba", "an" ...] because "an" overlaps "ba". The next match search will start from the last match's end, always.
If you want to find overlapping sequences, you need to use lookahead/lookbehind to shorten your match size so the matches themselves don't overlap: /(?=(..))/. Note that you have to introduce a capture group, since the match itself is an empty string in this case.
def substrings str
(0...str.length).flat_map{|i| (i...str.length).map{|j| str[i..j]}}.uniq
end
substrings("banana")
Result
[
"b",
"ba",
"ban",
"bana",
"banan",
"banana",
"a",
"an",
"ana",
"anan",
"anana",
"n",
"na",
"nan",
"nana"
]
or
def substrings str
(0...str.length).to_a.combination(2).map{|r| str[*r]}.uniq
end
Result
[
"b",
"ba",
"ban",
"bana",
"banan",
"banana",
"an",
"ana",
"anan",
"anana",
"nan",
"nana",
"na",
"a"
]
Here's another way that does not use a regex. I see now how it can be done with a regex, but I don't know why you'd want to, unless it's just an exercise.
def substrings(str)
arr = str.chars
(1..str.size).each_with_object([]) { |i,a|
a << arr.each_cons(i).to_a.map(&:join) }.flatten
end
substrings("banana")
#=> ["b", "a", "n", "a", "n", "a", "ba", "an", "na", "an", "na", "ban",
# "ana", "nan", "ana", "bana", "anan", "nana", "banan", "anana"]
If you want to include the word "banana", change str.size to str.size+1.
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.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I have an array of hashes:
my_array = [
{
:id => 1,
:name => "Bill"
},
{
:id => 2,
:name => "Joe"
},
{
:id => 3,
:name => "Bob"
}
]
How can I get an item passing the ID, for example, given 3 as the 'id' I'd like to get the hash: {"id": 3, "nome": "Bob"}.
UPDATE:
I discovered the answer, using the method .selec as follows:
my_array.select { |a| a[:id] == 1 }
What you have is a JSON string. You will need to parse it into an array of hashes first and then use Enumerable#find to get the item:
require 'json'
test = '[
{
"id": 1,
"nome": "Bill"
},
{
"id": 2,
"nome": "Joe"
},
{
"id": 3,
"nome": "Bob"
}
]'
# Parse into an array of hashes
hashes = JSON.parse(test)
foundItem = hashes.find { |item| item["id"] == 3}
puts foundItem
Since it looks like jSON you should parse as above if it is an actual array of Hashes you can do this
arr = [{"id" => 1,"nome"=> "Bill"},{"id"=> 2,"nome"=> "Joe"},{"id"=> 3,"nome"=> "Bob"}]
arr.select{|h| h["id"] == 3}
#=>[{"id"=> 3,"nome"=> "Bob"}]
This will return an Array of all matching Hash
To get a single value you can use
arr.select{|h| h["id"] == 3}.pop
#=>{"id"=> 3,"nome"=> "Bob"}
Which will return the last matching Hash Or as #KalmanHazins stated
arr.find{|h| h["id"] == 3}
#=>{"id"=> 3,"nome"=> "Bob"}
Which will return the first Hash that matches based on current order
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to remove partial duplicate value from an Array.
['John', 'Johnson', 'Mike', 'Tim', 'Timberland']
I want remove partial duplicate value.
in this case, I want keep longer string value.
['Johnson', 'Mike', 'Timberland']
Any good idea?
This is how I would do:
ary = ['John', 'Johnson', 'Mike', 'Tim', 'Timberland']
ary.select {|e| ary.grep(Regexp.new(e)).size == 1 }
# => ["Johnson", "Mike", "Timberland"]
Just do the following, in case when part is resided at the beginning of a word only:
array = ['John', 'Johnson', 'Mike', 'Tim', 'Brakatim', 'Weltimwel']
# => ["John", "Johnson", "Mike", "Tim", "Brakatim", "Weltimwel"]
array.reject {| v | " #{array.join( ' ' )} " =~ /\W#{v}\w/i }
# => ["Johnson", "Mike", "Tim", "Brakatim", "Weltimwel"]
Or in case when part is resided at the beginning of a word, and at the end or middle of it:
array = ['John', 'Johnson', 'Mike', 'Tim', 'Timberland', 'Brakatim', 'Weltimwel']
# => ["John", "Johnson", "Mike", "Tim", "Timberland", "Brakatim", "Weltimwel"]
array.reject {| v | " #{array.join( ' ' )} " =~ /\W#{v}\w|\w#{v}\W|\w#{v}\w/i }
# => ["Johnson", "Mike", "Timberland", "Brakatim", "Weltimwel"]
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 9 years ago.
Improve this question
Right now, I have a structure like this:
[
{ asin: "B000O3GCFU", name: "Thermos...", price: "$10.19" },
{ asin: "B0025Y6742", name: "Thermos...", price: "$12.19" }
# ...
]
So, an array of hashes.
How can I extract single keys and values of each of the hashes? Like:
[
{ asin: "B000O3GCFU" },
{ asin: "B0025Y6742" }
# ...
]
You can use map and create new hashes containing only "asin" on the fly:
a.map {|h| {:asin => h[:asin]}}
product_hash[:product].map do |product|
product.slice(:asin) # if you have activesupport
product.select { |key, val| key == :asin } # if you don't
end