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 4 years ago.
Improve this question
I have a array of hashes
arr = [{a: 1, b: 2, c:3}, {a:2, b:10, c:2}, {a:9, b:2, c:8}]
I need to add values of the by their respective keys. The output should be like
{a: 12, b: 14, c: 13} or [{a: 12, b: 14, c: 13}]
How can I achieve this?
arr.inject do |result_so_far, hash|
result_so_far.merge(hash) do |_, total_so_far, value_from_hash|
total_so_far + value_from_hash
end
end
inject in an array takes a value to start with and combines it with a previous result.
merge on a hash combines 2 hashes, using the block to define handling of duplicate keys, in this case by adding to the total so far for the key.
Another way could be we iterate each array element and each hash and add values to a new hash
new_hash = Hash.new(0)
arr.each { |hash| hash.each { |key, value| new_hash[key] += value } }
puts new_hash
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 2 years ago.
Improve this question
I have an array, and I need to print it out all on one line:
numbers = Array[[2, 4, 4, 5, 5, 7, 9]
Instead of separate lines how can I code this? I heard Array.join('') but I tried this code and it wouldn't run.
Always remember that the Ruby manual is your friend. If you read the manual for Array#join you will find some good candidates:
join(p1 = v1) public
Returns a string created by converting each element of the array to a string, separated by the given separator. If the separator is nil, it uses current $,. If both the separator and $, are nil, it uses an empty string.
[ "a", "b", "c" ].join #=> "abc"
[ "a", "b", "c" ].join("-") #=> "a-b-c"
So, now we can try:
numbers = [1, 2, 3, 4, 5]
puts numbers.join(" ")
Outputs:
1 2 3 4 5
Try
p numbers
This will print your array on a single line (which will obviously overflow depending on your window width).
You can use either method
puts numbers.join(', ');
or
puts numbers.inspect
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 5 years ago.
Improve this question
I can't seem to figure out a line of code to be able to do this. I have a hash that I would like to be able to pick out all of the keys that are at least 6 characters long.
Try this one
your_hash.keys.select { |k| k.length >= 6 }
as you want "length of values"
{a: 'carl', b: 'steve'}.map {|k, v| v.size }
# => [4, 5]
# select sizes values directly within the hash enumeration
{a: 'carl', b: 'steve'}.values.map {|v| v.size }
# => [4, 5]
# convert hash to array of values and then select the sizes values
{a: 'carl', b: 'steve'}.values.select {|v| v.size > 4 }
# => ["steve"]
# convert hash to array of values and then select values that has a condition
if you want more advanced topic on "Lazy" Enumeration http://www.eq8.eu/blogs/28-ruby-enumerable-enumerator-lazy-and-domain-specific-collection-objects
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 5 years ago.
Improve this question
I have got a list l = [:foo, :bar, :baz] and want to assign a varible into a hash h ={} programmatically.
Hash should look like
{ foo: { bar: { baz: some_value } } }
Note: the keys are variables!
Question:
How can I do this?
You could use inject on the reversed list :
l = [:foo, :bar, :baz]
h = l.reverse.inject(:some_value) do |value, key|
{ key => value }
end
p h
# {:foo=>{:bar=>{:baz=>:some_value}}}
reverse is used in order to build the innermost hash first, and keep building the nested hash outwards.
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 7 years ago.
Improve this question
Enumerator#peek returns next object in enumerator. But how to get current object?
I couldn't find any other solution than using index (for array).
Like so:
enum = [1,2,3].to_enum
#=> #<Enumerator: [1, 2, 3]:each>
enum.next #=> 1
enum.peek #=> 2
enum.peek #=> 2 # to show enumerator is not incremented
enum.next #=> 2
enum.peek #=> 3
enum.next #=> 3
enum.peek #=> StopIteration: iteration reached an end
If you need to know the current value of the enumerator, after executingenum.next, just save it to a variable: curr = enum.next. Enumerators are generally used with blocks, in which case the current value of the enumerator is assigned to the block variable. To my knowledge, there is no way to obtain the current value of the enumerator from the enumerator object.
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 got this tab :
["aaaaaaaaaaaaaaaaaaa",
"15/87/2014r",
"2453/NRc05",
"xxxxxxxxxxxxxxxxxxxxxxxxxx",
"Adaptée",
"09/12/2013",
"pub.pdf"]
And I only want "xxxxxxxxxxxxx" for example.
I found .next.element(s) but I got no idead of how to use it.. :/
Array#each returns an Enumerator:
arr = [1, 2, 3]
enum = arr.each
enum.next
#=> 1
enum.next
#=> 2
enum.next
#=> 3
enum.next
#=> StopIteration: iteration reached an end
Update
Regarding your comment
I have a array with some datas, and I wanted to save them in a hash with names like... {Name : aaaaa, First Name : bbbbbb} etc etc etc
Rather than calling next over and over again (I assume you are doing something like this):
data = ["John", "Doe"]
enum = data.each
hash = {}
hash[:first_name] = enum.next
hash[:last_name] = enum.next
# ...
You can combine two arrays with Array#zip and convert it to a hash using Array#to_h:
data = ["John", "Doe"]
keys = [:first_name, :last_name, :other]
keys.zip(data).to_h
#=> {:first_name=>"John", :last_name=>"Doe", :other=>nil}