On Dec 17, 11:42 am, Tom N. removed_[email protected] wrote:

How do I divide a number (integer) by 2 and get a result that is like:

half_periods = num_periods/2 +1

else

half_periods = num_periods/2

end

## Is there a better way?

Posted viahttp://www.ruby-forum.com/.

Here’s a few ways:

require “test/unit”

PERIODS = [1,2,3,4,5,6,7,8,9,10]

PER_HALF = [1,1,2,2,3,3,4,4,5,5]

class TestPeriods < Test::Unit::TestCase

def test_div_two_plus_mod_two

assert_equal(PER_HALF, PERIODS.map {|period| period / 2 + period %

2})

end

def test_plus_mod_two_div_two

assert_equal(PER_HALF, PERIODS.map {|period| (period + period %

2) / 2})

end

def test_plus_one_div_two

assert_equal(PER_HALF, PERIODS.map {|period| (period + 1) / 2})

end

def test_div_2_ceil

assert_equal(PER_HALF, PERIODS.map {|period| (period / 2.0).ceil})

end

def test_plus_1_div_two_floor

assert_equal(PER_HALF, PERIODS.map {|period| ((period + 1.0) /

2).floor})

end

def test_div_2_round

assert_equal(PER_HALF, PERIODS.map {|period| (period /

2.0).round})

end

end