To set i and its maximum and have a double iterator In Java, I would use for loops as follows:
for (i=1; i<10, i+=){
for (j=1; j<10; j++){
puts i (or whatever function)
}
}
I'm trying to figure out how to do this in Ruby. The for loops I've seen in Ruby are for ranges, and single iterator:
for i in (1..10)
puts i
end
or while loops
i = 1
while i < 10
puts i
i += 1
end
Are these while loops the (single iterator) Ruby equivalent of the Java I mentioned, or is there another way to do these for loops?
The "ruby-ish" way would be each
(1...10).each do |i|
puts i
end
or to double iterate
(1...10).each do
(1...10).each do |j|
puts j
end
end
As #maxwilliams and #sawa point out, (1...10) is 1 through 9 inclusive, (1..10) is 1 through 10 inclusive.
Why not do a nested loop?
for i in 1...10
for j in 1...10
puts i
end
end
By the way, the Ruby equivalent is for i in 1...10, not for i in 1..10.
In Ruby you rarely use the for loop. Actually, you never use it. In Ruby you use enumerators and blocks.
for (i=1; i<10, i+=){
for (j=1; j<10; j++){
puts i (or whatever function)
}
}
is equivalent to
(1...10).each do |i|
(1...10).each do |j|
puts j
end
end
Also note there is a difference between
(1..10).each do |i|
end
and
(1...10).each do |i|
end
The latter is equivalent to
(1..9).each do |i|
end
In fact, the .. will create an inclusive range whereas ... an exclusive range.
It is also worth to mention that in Ruby you rarely use indexes to loop items. Therefore, if your goal is to print out some elements in an array, your code should not be
(1..10).each do |i|
p #items[i]
end
rather you call each on the collection.
#items.each do |item|
p item
end
In certain cases, like in your question, you don't even need a range (when your loop starts from 1. You can use times.
9.times do |i|
9.times do |j|
puts j
end
end
In Ruby we don't use parenthesis. They are uncool.
This is an example for while statement in Ruby
while $i < $num do
puts "Value for i is #{i}"
$i +=1
end
And this is an example for for loop.
for i in 0..10
puts "Value of local variable is #{i}"
end
But there are more loops! Check this for more info http://www.tutorialspoint.com/ruby/ruby_loops.htm
But if you are Java programmer, you can check this link https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-java/
Related
I have this bit of code:
gates.each do |key, value, temp|
unless value.class == Output
temp = value.in1
gates.each do |k, v|
if v.out == temp
value.base_distance += 1
#do a thing
end
end
end
end
What I want to happen is when the #do a thing comment inside the conditional is reached it should break out of the inner .each loop and move on to the next instance of the outer .each loop, essentially executing a next. How would I do that from inside the conditional?
TL;DR use break.
Here is the MCVE:
[1,2].each do |o|
puts "Outer: #{o}"
[1,2,3].each do |i|
break if i.even?
puts "Inner: #{i}"
end
end
#⇒ Outer: 1
# Inner: 1
# Outer: 2
# Inner: 1
FWIW, one might pass an argument to break to be returned from the block. This might be needed to emulate the next after break:
[1,2].each do |o|
puts "Outer: #{o}"
inner =
[1,2,3].each do |i|
break :next if i.even?
puts "Inner: #{i}"
end
next if inner == :next
...
end
This is my program, Not getting expected output. This need to print Ascending order.Please help me on this
a=[5,7,6,4,1,3,2,8,9,10]
temp=0
i=0
j=0
a.each do |i|
a.each do |j|
if(i>j)
temp=i
i=j
j=temp
end
end
end
puts i
Well, you should not compare i>j, those are index values of an array. You should do a[i]>a[j]. And also swap values using array and not array_index. If it doesn't bring the output post the error log.
#example
a=[3,2,1]
a.each{|x| puts x}
#output:
3
2
1
This means that x represents values inside a, but if you tried to do something like this:
a=[3,2,1]
a.each{|x| x = 5}
array a will not change, to change the values you can do this (using each_index method):
a.each_index {|x| a[x]=5}
# if you printed the array it will contains three fives.
# Now a = [5,5,5]
# x now will be the indexes 0,1,2,...
so my final solution for you problem is:
a.each_index do |i|
a.each_index do |j|
if(a[i]<a[j])
temp=a[i]
a[i]=a[j]
a[j]=temp
end
end
end
print a
Another solution with for loop:
a=[5,7,6,4,1,3,2,8,9,10]
for i in 0..a.length-1 do
for j in i..a.length-1 do
if a[i]>a[j]
a[i],a[j] = a[j],a[i] #swap
end
end
end
print a
Note:
You had a problem with the condition, You have to use less than instead of greater than if you want to print then in Ascending Order, if you used my for way the greater than will be used, it is a matter of how your algorithm and your loop works.
Learn Ruby the Hard Way asks to rewrite a script:
i = 0
numbers = []
while i < 6
puts "At the top i is #{i}"
numbers.push(i)
i += 1
puts "Numbers now: ", numbers
puts "At the bottom i is #{i}"
end
puts "The numbers: "
numbers.each {|num| puts num}
using for-loops and the (0 .. 6) range. The only solution I can find to work uses the for-each construct, which the author says to avoid:
def range_loop(increment, upper_limit)
numbers = []
for number in (0...upper_limit)
puts "The number is : #{number}"
numbers.push(number)
end
puts "The numbers: "
for number in numbers
puts number
end
end
range_loop(1, 6)
How can I write this script using the each construct?
You can use Range object and Enumerable#each method for this goal:
(0...6).each do |i|
#some code here
end
You could also use upto
0.upto(6) {|x| p "The number is #{x}"}
I need to group numbers that are in numerical order from an array.
(using ruby 1.9.2, rails 3.2)
Example1:
[1,2,4,5,6]
Example2:
[1,3,4,6,7]
Example3:
[1,2,3,5,6]
Example4:
[1,2,4,5,7]
After grouping
Example1:
[[1,2],[4,5,6]]
Example2:
[[1],[3,4],[6,7]]
Example3:
[[1,2,3],[5,6]]
Example4:
[[1,2],[4,5],[7]]
You get the idea.
(What I'm actually doing is grouping days, not relevant though)
Thanks in advance!
I'm not sure what you'd call this operation, but it's a sort of grouping method based on the last element processed. Something like:
def groupulate(list)
list.inject([ ]) do |result, n|
if (result[-1] and result[-1][-1] == n - 1)
result[-1] << n
else
result << [ n ]
end
result
end
end
The Enumerable module provides a large number of utility methods for processing lists, but inject is the most flexible by far.
Perfect problem to use inject (aka reduce) with:
def group_consecutive(arr)
arr.inject([[]]) do |memo, num|
if memo.last.count == 0 or memo.last.last == num - 1
memo.last << num
else
memo << [ num ]
end
memo
end
end
See it run here: http://rubyfiddle.com/riddles/0d0a5
a = [1,2,4,5,7]
out = []
a.each_index do |i|
if out.last and out.last.last == a[i]-1
out.last << a[i]
else
out << [a[i]]
end
end
puts out.inspect
Let's say I have this each loop in Ruby.
#list.each { |i|
puts i
if i > 10
break
end
}
Where I want to loop through the list until a condition is met.
This stung me as "un Ruby'ish" and since I'm new to Ruby, is there a Ruby way to do this?
You can use Enumerable#detect or Enumerable#take_while, depending on the result you want.
#list.detect { |i|
puts i
i > 10
} # Returns the first element greater than 10, or nil.
As others have noted, a better style would be to first make your sub-selection and then act on it, e.g.:
#list.take_while{ |i| i <= 10 }.each{|i| puts i}
You could use take_while:
#list.take_while { |i| i <= 11 }.each { |i| puts i }