Floor division operator in Ruby

So, am I confused or does Ruby not have a floor division operator? (// in Python)

Are you looking for this: Class: Numeric (Ruby 2.4.1) (ruby-doc.org)

1 Like

No,

It divided a number by another and then rounds down to the nearest integer.

3 / 2

Yeilds

1.5




3 // 2

Yeilds

1

This will return the floor:

def floor_of_division_with_input
  prompts = ["Enter the first number:", "Enter the second number:"]
  defaults = ["3", "2"]
  input = UI.inputbox(prompts, defaults, "Floor Division Input")
  num1, num2 = input.map(&:to_i)

  result = (num1.to_f / num2).floor
  UI.messagebox("The floor of the division of #{num1} by #{num2} is: #{result}")
end

floor_of_division_with_input

And this returns the division:

def division_with_input
  prompts = ["Enter the first number:", "Enter the second number:"]
  defaults = ["3", "2"]
  input = UI.inputbox(prompts, defaults, "Floor Division Input")
  num1, num2 = input.map(&:to_i)

  result = (num1.to_f / num2)
  UI.messagebox("The floor of the division of #{num1} by #{num2} is: #{result}")
end

division_with_input

So it’s two characters in Python, and two whole paragraphs in Ruby.

Understood.

There is floor()

2 Likes

No, no. You could use:

(3.to_f / 2).floor

And:

(3.to_f / 2)

I figured you were using the Ruby Console, so the prompts were for that.

1 Like

Ah. No I’m using Ruby + extension.

Actually I’m trying to learn to code for the first time using brilliant, it’s teaching me Python, but the concept of coding in general will be very helpful in the future w Ruby.

Oh, well good luck on that endeavor. Should be fun to do for its own sake. Anything more is just a bonus.

1 Like

You’ve gotten some input before, but to further clarify:

In Ruby, everything is an object and the operation of the / operator depends on the classes of the two objects. If they are both Integers, integer division is performed, which yields the same result as the Python “floor divide”:

3 / 2 # integer division => 1

If one of them is a Float, the operator is smart enough to do floating point division:

3.0 / 2 # floating point division => 1.5
3 / 2.0 # floating point division => 1.5

So, whereas you could do what @3DxJFD showed, usually there is no need to use the floor method. You just make sure your objects are of the required type for the expected result.

3 Likes

Thanks for the clarification.