Tuesday, June 27, 2006

Numbers in Ruby

Let's play with Numbers. In Ruby, numbers without decimal points are called integers, and numbers with decimal points are usually called floating-point numbers or, more simply, floats. Here's the program RubyNumbers.rb
=begin
Ruby Numbers
Usual operators:
+ addition
- subtraction
* multiplication
/ division
=end

puts 1 + 2
puts 2 * 3
# Integer division
# When you do arithmetic with integers, you'll get integer answers
puts 3 / 2
puts 10 - 11
puts 1.5 / 2.6
Questions asked by the participants:
1. Jatinder Singh - How do I get the integer result for the following operation (the desired output is 2) - puts 5.5/2
Answer: Try this -
num = 5.5 /2
puts num
puts num.to_int


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

4 Comments:

Blogger SatishTalim said...

The output for this program should be:

>ruby RubyNumbers.rb
3
6
1
-1
0.576923076923077
>Exit code: 0

9:54 AM  
Blogger Jatinder Singh said...

how do I get the integer result for following operation(the desired output is 2)
puts 5.5/2

1:03 PM  
Blogger SatishTalim said...

Jatinder the answer is:
num = 5.5 /2
puts num
puts num.to_int

1:12 PM  
Blogger शंतनु said...

num = (5.5/2).to_i

also works

5:18 PM  

Post a Comment

Links to this post:

Create a Link

<< Home