I have something like this:
[#TrajectoryMeasurement depth: 0, move_e: 234>,
#TrajectoryMeasurement depth: 1475, move_e: 123>]
How to convert it to:
[[0, 234], [1475,123]]
If it's an array of objects as I suspect you can use the #collect method on Array:
array = [#TrajectoryMeasurement depth: 0, move_e: 234>,
#TrajectoryMeasurement depth: 1475, move_e: 123>]
array.collect { |x| [x.depth, x.move_e] }
# => [[0, 234], [1475, 123]]
Supposing you really had a hash, all you need is calling .to_a to get exactly what you asked for.
{a:1, b:1}.to_a
=> [[:a, 1], [:b, 1]]
Alas, as it was said before, it wouldn't see, what you have there is a Hash, unless that's an ad-hoc representation of it.
Depending on the structure of your hash you might also want to have a look at .flatten.
Related
I have a hash that contains numbers as such:
{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}
it needs to be converted into an array like:
[[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]]
i tried my hash.values which gets me:
[0.07398921877505593, 0.07400253683443543, 0.07402917535044515]
I have tried multiple ways but i just started learning ruby.
try this:
{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}.to_a
#=> [[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]]
Definitely use the Hash#to_a method, which will produce exactly what you are looking for.
{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}.to_a
=> [[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]]
Hash#values will give you only the values of each element in the hash, while Hash#keys will give you just the keys. Fortunately, the default behavior of to_a is what you are looking for.
How do I serialize an array and deserialize it back from a string? I tried the following code, but it doesn't really return the original array of integers but does for the array of strings.
x = [1,2,3].join(',') # maybe this is not the correct way to serialize to string?
=> '1,2,3'
x = x.split(',')
=> [ '1', '2', '3' ]
Is there a way to get it back to integers without having the .collect{ |x| x.to_i }?
The standard way is with Marshal:
x = Marshal.dump([1, 2, 3])
#=> "\x04\b[\bi\x06i\ai\b"
Marshal.load(x)
#=> [1, 2, 3]
But you can also do it with JSON:
require 'json'
x = [1, 2, 3].to_json
#=> "[1,2,3]"
JSON::parse(x)
#=> [1, 2, 3]
Or YAML:
require 'yaml'
x = [1, 2, 3].to_yaml
#=> "---\n- 1\n- 2\n- 3\n"
YAML.load(x)
#=> [1, 2, 3]
Split is just a tool for chopping up strings - it doesn't know where that string came from.
There are many ways of serialising data: YAML, JSON and Marshal being three that are part of the Ruby Standard Library. All distinguish between strings, integers and so on.
There are pros and cons for each. For example, loading Marshal data from an untrusted source is dangerous and Marshal isn't good if you need to exchange the data with non-Ruby code. JSON is usually a good allrounder.
This is my hash.
=> {"f11"=>1, "f12"=>3, "f13"=>3, "f07"=>5, "f10"=>1}
I'd like to sort by the values largest to smallest and then make an array out of the keys.
=> ["f07", "f12", "f13", "f11", "f10"]
Here's a one-liner for you (I love ruby!):
h.keys.sort {|a, b| h[b] <=> h[a]}
Hope that helps!
Hash has the Enumerable module mixed in which provides us with methods like sort and sort_by.In this situation we can use sort_by to get a collection by order of values.
h={"f11"=>1, "f12"=>3, "f13"=>3, "f07"=>5, "f10"=>1}
h.sort_by{ |key, value| -value }
=> [["f07", 5], ["f12", 3], ["f13", 3], ["f11", 1], ["f10", 1]]
Even shorter!:
h.keys.sort_by{|a| h[a]}.reverse
a = {"f11"=>1, "f12"=>3, "f13"=>3, "f07"=>5, "f10"=>1}
b = Hash[a.sort_by{|k,v| v}]
puts b.keys.reverse
I'm fairly new to Ruby/Rails, and I'm trying to figure out how to split a {"key" => ["val1", "val2"]} hash into a {"key" => "val1", "key" => "val2"} hash. I feel like I should flatten the hash and somehow build a new one up, but I'm unsure how to approach the problem. Thanks!
EDIT: Haha, shows how blinded I was by the trees to not see the forest. Can't believe I made such a silly mistake. Thanks to everyone who shook me awake.
You cannot have duplicate keys in a Hash.
Also, why in the world would you want to do this? IMHO the way you have it now is perfectly fine.
A Hash by definition cannot have the same key present more than once. Would you instead like an Array of arrays?
[['key','val1'],['key','val2']]
If so, and if every hash key is an array of values, then you can do this:
devalues = { a:[1,2,3], b:[4], c:[5,6] }
exploded = devalues.map{ |k,vs| ([k]*vs.length).zip(vs) }.flatten(1)
p exploded
#=> [[:a, 1], [:a, 2], [:a, 3], [:b, 4], [:c, 5], [:c, 6]]
Note that flatten(1) is Ruby 1.8.7+ only
Edit: Per Nakilon's comment below, this can be a hair simpler in Ruby 1.9.2+:
exploded = devalues.flat_map{ |k,vs| ([k]*vs.length).zip(vs) }
Edit: Or per #tokland's comment below, even shorter/better using Array#product:
exploded = devalues.flat_map{ |k,vs| [k].product(vs) }
I have an array of hashes, and I want the unique values out of it. Calling Array.uniq doesn't give me what I expect.
a = [{:a => 1},{:a => 2}, {:a => 1}]
a.uniq # => [{:a => 1}, {:a => 2}, {:a => 1}]
Where I expected:
[{:a => 1}, {:a => 2}]
In searching around on the net, I didn't come up with a solution that I was happy with. Folks recommended redefining Hash.eql? and Hash.hash, since that is what Array.uniq is querying.
Edit:
Where I ran into this in the real world, the hashes were slightly more complex. They were the result of parsed JSON that had multiple fields, some of which the values were hashes as well. I had an array of those results that I wanted to filter out the unique values.
I don't like the redefine Hash.eql? and Hash.hash solution, because I would either have to redefine Hash globally, or redefine it for each entry in my array. Changing the definition of Hash for each entry would be cumbersome, especially since there may be nested hashes inside of each entry.
Changing Hash globally has some potential, especially if it were done temporarily. I'd want to build another class or helper function that wrapped saving off the old definitions, and restoring them, but I think this adds more complexity than is really needed.
Using inject seems like a good alternative to redefining Hash.
I can get what I want by calling inject
a = [{:a => 1},{:a => 2}, {:a => 1}]
a.inject([]) { |result,h| result << h unless result.include?(h); result }
This will return:
[{:a=>1}, {:a=>2}]
Ruby 1.8.7+ will return just what you have expected:
[{:a=>1}, {:a=>2}, {:a=>1}].uniq
#=> [{:a=>1}, {:a=>2}]
I've had a similar situation, but hashes had keys. I used sorting method.
What I mean:
you have an array:
[{:x=>1},{:x=>2},{:x=>3},{:x=>2},{:x=>1}]
you sort it (#sort_by {|t| t[:x]}) and get this:
[{:x=>1}, {:x=>1}, {:x=>2}, {:x=>2}, {:x=>3}]
now a bit modified version of answer by Aaaron Hinni:
your_array.inject([]) do |result,item|
result << item if !result.last||result.last[:x]!=item[:x]
result
end
I've also tried:
test.inject([]) {|r,h| r<<h unless r.find {|t| t[:x]==h[:x]}; r}.sort_by {|t| t[:x]}
but it's very slow. here is my benchmark:
test=[]
1000.times {test<<{:x=>rand}}
Benchmark.bmbm do |bm|
bm.report("sorting: ") do
test.sort_by {|t| t[:x]}.inject([]) {|r,h| r<<h if !r.last||r.last[:x]!=h[:x]; r}
end
bm.report("inject: ") {test.inject([]) {|r,h| r<<h unless r.find {|t| t[:x]==h[:x]}; r}.sort_by {|t| t[:x]} }
end
results:
Rehearsal ---------------------------------------------
sorting: 0.010000 0.000000 0.010000 ( 0.005633)
inject: 0.470000 0.140000 0.610000 ( 0.621973)
------------------------------------ total: 0.620000sec
user system total real
sorting: 0.010000 0.000000 0.010000 ( 0.003839)
inject: 0.480000 0.130000 0.610000 ( 0.612438)
Assuming your hashes are always single key-value pairs, this will work:
a.map {|h| h.to_a[0]}.uniq.map {|k,v| {k => v}}
Hash.to_a creates an array of key-value arrays, so the first map gets you:
[[:a, 1], [:a, 2], [:a, 1]]
uniq on Arrays does what you want, giving you:
[[:a, 1], [:a, 2]]
and then the second map puts them back together as hashes again.
You can use (tested in ruby 1.9.3),
[{a: 1},{a: 2},{a:1}].uniq => [{a:1},{a: 2}]
[{a: 1,b: 2},{a: 2, b: 2},{a: 1, b: 3}].uniq_by {|v| v[:a]} => [{a: 1,b: 2},{a: 2, b: 2}]
The answer you give is similar to the one discussed here. It overrides the hash and eql? methods on the hashes that are to appear in the array which then makes uniq behave correctly.
found on google
http://mikeburnscoder.wordpress.com/2008/01/18/uniquify-an-array-of-hashes-in-ruby/
The pipe method on arrays (available since 1.8.6) performs set union (returning an array), so the following is another possible way to get unique elements of any array a:
[] | a