Ruby Refuses to Divide Correctly

Ruby Refuses to Divide Correctly

It's doing integer division.

Basically, 25 is an integer (a whole number) and so is 50, so when you divide one by the other, it gives you another integer.

25 / 50 * 100 = 0.5 * 100 = 0 * 100 = 0

The better way to do it is to first multiply, then divide.

25 * 100 / 50 = 2500 / 50 = 50

You can also use floating point arithmetic explicitly by specifying a decimal point as in:

25.0 / 50.0 * 100 = 0.5 * 100 = 50

Why is division in Ruby returning an integer instead of decimal value?

It’s doing integer division. You can make one of the numbers a Float by adding .0:

9.0 / 5  #=> 1.8
9 / 5.0 #=> 1.8

I am trying to calculate `10 * (50 / 100)` and I got back `0` but when I did `10 * 50 / 100` I got back `5`!

50 / 100 is 0 because you are using integer division. The result is truncated to an integer.

Performing the multiplication first works because then the division gives a whole number.

You could perform the calculation using floats instead of integers: 50.0 / 100.0 == 0.5, then round the result to an integer at the end of the calculation.

proportion = 50.0 / 100.0
result = (10 * proportion).round
return result

See it working online: ideone

Ruby: Unable to do math operations with two arguments

The code is correct, but it doesn't make a lot of sense. You are passing the values to the initializer, therefore I expect your code to be used as it follows

c = Calculator.new(7, 8)
c.add
# => 15

and it's probably the way you are calling it. However, this is not possible because you defined add() to take two arguments. Therefore, you should use

c = Calculator.new(7, 8)
c.add(1, 2)
# => 3

But then, what's the point of passing x and y to the initializer? The correct implementation is either

class Calculator
attr_accessor :x, :y

def self.description
"Performs basic mathematical operations"
end

def initialize(x, y)
@x = x.to_i
@y = y.to_i
end

def add
x + y
end

def subtract
x - y
end
end

or more likely

class Calculator
def self.description
"Performs basic mathematical operations"
end

def initialize
end

def add(x, y)
x.to_i + y.to_i
end

def subtract(x, y)
x.to_i - y.to_i
end
end

Dividing elements of a ruby array into an exact number of (nearly) equal-sized sub-arrays

You're looking for Enumerable#each_slice

a = [0, 1, 2, 3, 4, 5, 6, 7]
a.each_slice(3) # => #<Enumerator: [0, 1, 2, 3, 4, 5, 6, 7]:each_slice(3)>
a.each_slice(3).to_a # => [[0, 1, 2], [3, 4, 5], [6, 7]]

How to split string into 2 parts after certain position

This should do it

[str[0..5], str[6..-1]]

or

 [str.slice(0..5), str.slice(6..-1)]

Really should check out http://corelib.rubyonrails.org/classes/String.html



Related Topics



Leave a reply



Submit