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
Related
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
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 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}
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 8 years ago.
Improve this question
I have str = "1, 2, a, 3, 4, z"
I want to use Regex to find and add .3 to the end of all the digits and a colon : to the beginning of all the characters. So the desired output would be:
"1.3, 2.3, :a, 3.3, 4.3, :z"
Can I do that with gsub in Ruby? Is that the most efficient way?
String#gsub accepts optional block. The return value of the block is used as substitution string.
str = "1, 2, a, 3, 4, z"
str.gsub(/\d+|[a-z]+/i) { |x| x =~ /\d/ ? x + '.3' : ':' + x }
# => "1.3, 2.3, :a, 3.3, 4.3, :z"
using capturing group:
str.gsub(/(\d+)|([a-z]+)/i) { $1 ? $1 + '.3' : ':' + $2 }
# => "1.3, 2.3, :a, 3.3, 4.3, :z"
From String#gsub documentation:
If replacement is a String it will be substituted for the matched
text. It may contain back-references to the pattern’s capture groups
of the form \d, where d is a group number, or \k, where n is a
group name. If it is a double-quoted string, both back-references must
be preceded by an additional backslash. However, within replacement
the special match variables, such as $&, will not refer to the current
match.
The solution:
str = "1, 2, a, 3, 4, z"
str.gsub(/(\d)+/, '\1.3').gsub(/([a-z])+/i, ':\1')
# => "1.3, 2.3, :a, 3.3, 4.3, :z"
Non-regexp and gsub version:
str = "1, 2, a, 3, 4, z"
result = str.split(', ').map do |chr|
case chr.downcase
when 'a'..'z' then ":#{chr}"
when '1'..'9' then "#{chr}.3"
end
end.join(', ')