Read Effective Python Memo Item 12 Avoid using else blocks after for and while loops, and wonder how to write it as Ruby. Became.
a = 4
b = 9
for i in range(2, min(a, b) + 1):
print('Testing', i)
if a % i == 0 and b % i == 0:
print('Not coprime')
break
else:
print('Coprime')
The ʻelse` clause is executed when the loop ends uninterrupted. Sure, it's not intuitive. I'll do this with Ruby.
Ignoring the ʻelse` clause, in the case of Ruby,
a = 4
b = 9
(2..[a, b].min).each do |i|
puts "Testing: #{i}"
if (a % i).zero? && (b % i).zero?
puts "Not coprime"
break
end
end
It will be. ʻEachreturns
self, so if the iteration ends without
break,
2 .. [a, b], that is, the true value is returned, and if
break,
nil`, that is, A false value is returned.
So, if you connect with ʻand`, it seems to work.
a = 4
b = 9
(2..[a, b].min).each do |i|
puts "Testing: #{i}"
if (a % i).zero? && (b % i).zero?
puts "Not coprime"
break
end
end and puts "Coprime"
For the time being, it went well. But it's not beautiful.
To use &&
, you need to use puts ("Coprime")
or (puts" Coprime ")
to strengthen the connection between puts
and"Coprime"
.
I also thought about how to get Ruby Poku puts
out.
a = 4
b = 9
puts (2..[a, b].min).each_with_object("Coprime") { |i|
puts "Testing: #{i}"
if (a % i).zero? && (b % i).zero?
break "Not coprime"
end
}
a = 4
b = 9
puts "Coprime".tap {
(2..[a, b].min).each do |i|
puts "Testing: #{i}"
if (a % i).zero? && (b % i).zero?
break "Not coprime"
end
end
}
All are difficult to understand.
As you can see in "Effective Python", it seems best to cut out to a method without doing something like for-else
.
def coprime?(a, b)
(2..[a, b].min).each do |i|
return false if (a % i).zero? && (b % i).zero?
end
true
end
puts coprime?(4, 9) ? "Coprime" : "Not coprime"
Recommended Posts