Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ruby modulo is different from java/other lang ?

Tags:

java

ruby

modulo

i am basically coming from java background and struggling to understand the modulo operation in Ruby.

(5 % 3)     
(-5 % 3)    
(5 % -3)    
(-5 % -3) 

The above operation in Java yields, 2 -2 2 -2

But in Ruby, the same expression yields 2 1 -1 -2 .

How logically ruby is good at this? How the module operation is implemented in Ruby ? If the same operation is defined as a web services, how both services can match the logic.

like image 268
Karthikeyan Avatar asked Nov 20 '13 15:11

Karthikeyan


People also ask

Is Ruby better than Java?

Ruby has a clear advantage over Java when it comes to developing web applications, especially when used with the Rails framework. One of the main reasons why developers choose Ruby over Java is that writing a function in Ruby requires less lines of code than in Java.

What is modulo Ruby?

The modulo() is an inbuilt method in Ruby returns the modular value when two numbers are divided. It returns the value of a modulo b. Syntax: a.modulo(b) Parameters: The function needs two number whose modulus on division is returned. Return Value: It returns the modulus when two numbers are divided.

Is Ruby similar to Java?

Ruby is an interpreted scripting language, whereas Java is a compiled programming language. Ruby is similar to Java in that both are object-oriented languages and are strongly typed. But, Ruby is dynamically typed, whereas Java is statically typed.

Why is modulo useful?

The modulo operator is used to compute the remainder of an integer division that otherwise lost. It's useful to do simple things like figuring out if a given number is even or odd, as well as more complex tasks like tracking the next writing position in a circular array.


2 Answers

In Java, the result of the modulo operation has the same sign as the dividend.

In Ruby, it has the same sign as the divisor. remainder() in Ruby has the same sign as the dividend.

You might also want to refer to modulo operation.

like image 148
devnull Avatar answered Sep 29 '22 07:09

devnull


Because Ruby defines x.modulo(y) to be x-y*(x/y).floor. See ruby-doc.org

like image 28
pjs Avatar answered Sep 29 '22 07:09

pjs