Problems with loops in Ruby Code [closed] - ruby

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 8 years ago.
Improve this question
Hey I have an array with numbers in it.
Now I want to divide the value at 17th position of the array by the value at the first position of the array, then the 18th by the second, and so on. The results should build a new array.
Then I want to scan all values of the new array and if two or more successive values are bigger than 1.2, I want to add the result of dividing the first by the last value of that row for all of successive values. If one value is 1.2 and the next for example 0.8, the values of the array should not be changed.
Here is my code:
a = [1,2,3,4,5,9,5,13,14,17,19,23,19,34,46,12,13,45,46,67,78,79]
b = Array.new
c = Array.new
a.each_cons(18) { |c| b.push(c[17]/c[0] }
Do you have an idea how to implement the condition?

I think this will do it, although I selectively interpreted some things from your question. Specifically, in "of that row for all of successive values," does "row" refer to the sliding block from each_cons? Ditto for "all of successive values."
catch (:done) do
for i in 2..b.length do
b.each_cons(i) do |d|
for j in 2..d.length do
d.each_cons(j) do |g|
if g.all? { |g| g > 1.2 }
c = b.map { |f| f + (d[0].to_f/d[i-1].to_f) }
break
end
if !c.empty? then throw :done end
end
end
end
end
end
puts c

Related

Difference between set and hash? [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 6 years ago.
Improve this question
Seems to me like the only real difference between a hash and a set is that sets don't have keys. Are there any other important differences?
Not all hashes are sets, but a hash can be used as a set.
Sets are collections where the values are...
Unordered
Unique
A hash with only keys matches that, so sets are often implemented as a hash with only keys. The keys are used as the values in the set, so they can be quickly looked up and iterated through.
In Perl it's very common to put a list into a hash to deduplicate it and work with it as a set.
my %set = map { $_ => 1 } #values;
Ruby's Set class is a thin wrapper around a hash. For example, here's Set#add.
# File set.rb, line 312
def add(o)
#hash[o] = true
self
end
If you want to check if something is in the set, just check if its in the hash, an O(1) lookup.
# File set.rb, line 214
def include?(o)
#hash[o]
end
Most set operations, such as intersections and unions are very fast. Intersection just checks if any keys in one hash are in the other, an O(n) operation (leaving aside key collisions). Here's how Ruby does it.
def intersect?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
if size < set.size
any? { |o| set.include?(o) }
else
set.any? { |o| include?(o) }
end
end
Union combines both hashes into one new hash, also an O(n) operation.
def |(enum)
dup.merge(enum)
end

updating array based on symbols Ruby [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 6 years ago.
Improve this question
How does one update the array based on symbols? Like
data = []
string = "Hello"
if( !data.include? string )
count += 1
data.insert(-1, {
label: string,
value: count,
})
else
#logic to change count value if string is encountered again
end
I was thinking of finding the index where the string lies and then delete that to insert another updated values at that index. Is this the right approach?
Just use find to get the match, provided its the only one in the array. You can use select to get multiple matches. After that just update the count
As your example is taken out of context and contains errors, I've taken a liberty to make a more complete example.
data = []
strings = ["Hello", "Bye", "Hello", "Hi"]
strings.each do |string|
hash = data.find{ |h| h[:label] == string }
if hash.nil?
data << {label: string, value: 1}
else
hash[:value] += 1
end
end

How to return a result composed of two changed has_and_belongs_to_many relations [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
r is an array that has three items that is the result of
r = Part.components.products.uniq
where Part HABTM Component and Component HABTM Product.
Why does this code:
class Array
def p_object_ids
puts each { object_id }.join(", ")
end
end
p r.class
r.p_object_ids
p r.count
generate this output:
Array
#<User:0x00000006535650>, #<User:0x000000065338f0>, #<User:0x000000065336e8>
1
It returns 1 when it's not really an array of three items, but an Array containing a single ActiveRecord. The correct implementation of what I was looking for turned out to be:
class Part
def products
Prooduct.joins(components: :part).where(parts: {id: self.id})
end
end
and not
self.components.map(&:products).uniq.to_a

How to break inner loop and next for outer loop in ruby? [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
I dont want to use if statement.
count = 0
10.times do |i|
all = (i..20).collect{ |ii| ii < rand(30) || break }
count+=1 if all # i dont want to use `if` statement
end
p count
How can I do that?
I got something in the similar matter:
count = 0
10.times do |i|
(i..20).collect{ |ii| ii < rand(30) || break } || next
count += 1
end
So it is just boolean algebra. if condition is taken place, when all, i.e. result of collect method, isn't nil, so we need to next keyword worked, when result of collect is nil. Therefore we just set or operator between collect and next, in order to next is occuring when result of collect is nil.
count = (0..9).count { |i| (i..20).all?{ |j| j < rand(30) } }

How does ruby works with array of arrays [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 am facing something i do not fully understand.
I have an array whose elements are arrays.
So I have two nested loops, in the inner loop I fill my inner array
then in the outer loop i fill the outer array with the inner array.
arr=[]
mat=[]
for m in (0..1)
for k in (0..1)
arr[k]=rand.to_s
end
mat[m]=arr
end
At the end my matrix is filled with two array; each array contains the values calculated in the last iteration.
If i want the first element in matrix to contain the first computed array I have to reinitialize the arr object at each loop.
So it seems that assignment is made by reference until the arr object is "cleaned". If I add
mat[m]=arr
arr=[]
all works as expected: mat[0] will contain the array computed in the first loop, and mat[1] will contain the array computed in the second loop.
Is this by design or is it an undesired side effect?
This is happening only if I assign arrays as array elements. If if fill an array with simple string variables in a loop all goes as expected.
I know that it is good programming practice to avoid reusing objects, but this behavior is anyway strange.
Your problem is that your arr variable's contents is being overwritten with each iteration: the arr[k] overwrites whatever is in there already. The arr variable needs to be local to the block instead:
mat = []
2.times do # avoid for... use iterators instead
row = []
2.times do
row << rand.to_s
end
mat << row
end
I like the approach of using hashes instead of multidimensional arrays.
How about this:
def creat­e_matrix x, y, conte­nt = nil, &block
rows = (0...x­).to_a
cols = (0...y­).to_a
indices = rows.­product cols
matrix = {}
indices.ea­ch { |inde­x| matri­x[index] = ( block­_given? ? yield­( index ) : conte­nt ) }
matrix
end
Then do:
matrix = create_matrix( 2, 2 ) { rand.to_s }
You will get a hash, that you can access like this:
matrix[[0, 1]] #note the double brackets
Another way of doing it:
(1..4).map{rand}.each_slice(2).to_a

Resources