1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
cap_growth = 5 v = (@property.current_value / 100 * cap_growth) + @property.current_value puts v v = (v / 100 * cap_growth) + v puts v v = (v / 100 * cap_growth) + v puts v v = (v / 100 * cap_growth) + v puts v v = (v / 100 * cap_growth) + v puts v v = (v / 100 * cap_growth) + v puts v v = (v / 100 * cap_growth) + v puts v v = (v / 100 * cap_growth) + v
Refactorings
No refactoring yet !
typefreak
September 30, 2007, September 30, 2007 14:05, permalink
Why don't you use a loop?
(Untested)
1 2 3 4 5 6 7
cap_growth = 5 v += (@property.current_value / 100 * cap_growth) for i in (0..7) puts v v += v / 100 * cap_growth end
anshkakashi
September 30, 2007, September 30, 2007 15:14, permalink
Here is the same thing, a bit shorter.
1 2 3 4 5 6 7
cap_growth = 5 v = @property.current_value 8.times do puts v += v/ 100 * cap_growth end
bauser
September 30, 2007, September 30, 2007 16:29, permalink
I'm not sure what you are trying to do, but if you wanted to keep track of the values, you could do something like...
1
a = (0..8).inject([]) {|a, i| a << (v += (v/100) * cap_growth)}
jtm
October 1, 2007, October 01, 2007 07:45, permalink
Using a simple formula to calculate the final value. Not useful for every value, but does jump right to the end without looping.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#!/usr/bin/ruby -w # # Using geometric series to calculate value of: # ar^n + ar^(n-1) + ... + ar^2 + ar + a # # = a(1-r^(n+1))/(1-r) # # also adding a starting savings to get: # # a(1-r^(n+1))/(1-r) + sr^n # puts "Enter Starting Amount" s = gets.chomp.to_f puts "Enter savings per year" a = gets.chomp.to_f puts "Enter savings rate of return" r = gets.chomp.to_f puts "Enter number of years" n = gets.chomp.to_f value = a*(1-r**(n+1))/(1-r) + s*r**n value = (value*100).round / 100.0 puts "Saved: $#{value} in #{n} years"
hungryblank
October 1, 2007, October 01, 2007 09:38, permalink
This is just an example on how you can wrap the calculation in a class.
one method provide the calculation of the value at any time in the future.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Investment < Struct.new(:start_year, :start_value, :interest_rate) def value_at(year) start_value * (1 + interest_rate) ** (year - start_year) end end # # Sample usage # we invest 100 in 1990 at 5% interest and want to know the value per # every year from 1990 to 2005 i = Investment.new(1990, 100, 0.05) (1990..2005).each { |year| puts i.value_at(year) }
there must be a better way to do this.
im doing something like the code below to calculate compund interest and print the result each year