Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Modulo Division

Tags:

ruby

modulo

So I made a program to do modulo division in Ruby, using a module:

module Moddiv
    def Moddiv.testfor(op1, op2)
        return op1 % op2
    end
end

Program:

require 'mdivmod'
print("Enter the first number: ")
gets
chomp
firstnum = $_
print("Enter the second number: ")
gets
chomp
puts
secondnum = $_
puts "The remainder of 70/6 is " + Moddiv.testfor(firstnum,secondnum).to_s

When I run it with two numbers, say 70 and 6, I get 70 as the output! Why is this happening?

like image 585
Billjk Avatar asked May 08 '26 17:05

Billjk


2 Answers

It's because firstnum and secondnum are the strings "70" and "6". And String#% is defined - it's the formatted-output operator.

Since "70" is not a format string, it's treated as a literal; so "70" % "6" prints "6" formatted according to the template "70", which is just "70".

You need to convert your input with firstnum = $_.to_i etc.

like image 63
Chowlett Avatar answered May 10 '26 09:05

Chowlett


Modulo seems to have trouble with strings, for example, in irb:

"70" % "6" => "70"

try making your return statement:

return op1.to_i % op2.to_i
like image 42
coder_tim Avatar answered May 10 '26 10:05

coder_tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!