Current object in Enumerator [closed] - ruby

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.

Related

How to print a Ruby Array on one line [closed]

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

Ruby - Add values of array of hash by respective keys [closed]

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

Filter hash keys of certain length? [closed]

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

Ruby : How to take the next element of a array? [closed]

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}

Ruby sort - why rspec error when "expected: [7, 6, 5, 5, 4, 3, 3]" seems the same as "got: [7, 6, 5, 5, 4, 3, 3]"? [closed]

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
Result:
Failures:
1) An usual sorter sorts downwards by default
Failure/Error: [a,b,c,d,e,f,g].sort.should == [7,6,5,5,4,3,3]
expected: [7, 6, 5, 5, 4, 3, 3]
got: [7, 6, 5, 5, 4, 3, 3] (using ==)
# ./downsort_spec.rb:13:in `block (2 levels) in <top (required)>'
Finished in 0.00077 seconds
Test:
require_relative 'my_sorter.rb'
describe "A usual sorter" do
it "sorts downwards by default" do
my_array= [3,5,7,5,3,6,4,2,5,6]
a=MySorter.new(3)
b=MySorter.new(5)
c=MySorter.new(7)
d=MySorter.new(5)
e=MySorter.new(3)
f=MySorter.new(6)
g=MySorter.new(4)
[a,b,c,d,e,f,g].sort.should == [7,6,5,5,4,3,3]
end
end
Code:
class MySorter
include Comparable
attr_reader :value
def initialize(value)
#value = value
end
def <=> (other)
if value > other.value then
-1
elsif value < other.value then
1
else
0
end
end
def inspect
#value
end
end
I have a very simple sort for now, the intent will be a more complex one once I have this working (hence the detail in the comparison method).
You are comparing an array of MySorter objects to an array of Fixnums. You need to change this:
[a,b,c,d,e,f,g].sort.should == [7,6,5,5,4,3,3]
to
[a,b,c,d,e,f,g].sort.map(&:value).should == [7,6,5,5,4,3,3]
An alternative to the answer involving converting the array of MySorter values into an array of Fixnum values is to expand the capability of your <=> method to handle Fixnum comparisons by including the following as the first statement in the block:
other = MySorter.new(other) if other.class == 'Fixnum'
There may be more elegant/efficient mechanisms to achieve this, but you get the idea.
Your problem comes in because you have not overridden == in MySorter.
You have an array of MySorter objects which you are then attempting to compare to the array of fixnums, whereas what you want to compare is the contents of the MySorter objects.
Define
def == (other)
other == value
end
in MySorter and your problem is resolved. I think the default ruby == operator compares object ids or similar, which will obviously fail in your vanilla case, since a MySorter is not a Fixnum.

Resources