E0dabbf83e6c56adc987e069e4b83a2b

Noob to Ruby here. Any way to make this cleaner?

class RSExp

	def equate(xp)
		(xp + 300 * (2 ** (xp.to_f / 7))).floor
	end

	def level_to_xp(level)
		xp = 0.0

		(1...level).each do |lvl|
			xp += equate(lvl)
		end

		(xp / 4).floor
	end

	def xp_to_level(xp)
		level = 1

		while level_to_xp(level) < xp
			level += 1
		end

		level
	end

end

rs = RSExp.new

(1...100).each do |lvl|
	puts("level #{lvl}: #{rs.level_to_xp(lvl)}")
end

Refactorings

No refactoring yet !

5071c5b861341c0dcfcf6ac86327701f

Tien Dung

September 20, 2008, September 20, 2008 23:34, permalink

1 rating. Login to rate!
# Duplicated post, please help to delete
5071c5b861341c0dcfcf6ac86327701f

Tien Dung

September 20, 2008, September 20, 2008 23:57, permalink

No rating. Login to rate!

Man, you made your code over complicated and ugly.

* Why you use class as a namespace?
* Why you create a function called xp_to_level and don't use it in your program?
* Why you don't reuse computation result from previous step?
* Why you name a function that no one can understand what does it mean without any comment? (what does xp stand for).

Here is an equivalent program that is faster, clearer and shorter.

def equate(level)
  (level + 300 * (2 ** (level / 7.0))).floor
end

x = 0
(1...100).each do |level|
  puts("level #{level}: #{(x/4).floor}")
  x = x + equate(level)
end
A8d3f35baafdaea851914b17dae9e1fc

Adam

September 22, 2008, September 22, 2008 01:45, permalink

3 ratings. Login to rate!
class RandomClassName < Struct.new(:level)
  RANDOMLY_CHOSEN_CONSTANT_1 = 300
  RANDOMLY_CHOSEN_CONSTANT_2 = 7.0
  
  def some_kind_of_conversion_from_level
    (calculation_method_just_because_by_level / 4.0).floor
  end
  
  def to_s
    "level #{level}: #{some_kind_of_conversion_from_level}"
  end
  
  protected
    def calculation_method_just_because_by_level
      1.enum_for(:upto, level).inject do |randomly_chosen_name,name_that_describes_what_this_is|
        randomly_chosen_name + calculation_method_just_because(name_that_describes_what_this_is)
      end
    end    
  
    def calculation_method_just_because(randomly_chosen_variable)
      interesting_calcuation = (randomly_chosen_variable / RANDOMLY_CHOSEN_CONSTANT_2) ** 2
      (randomly_chosen_variable + RANDOMLY_CHOSEN_CONSTANT_1 * interesting_calcuation).floor
    end
end

100.times do |level|
  puts RandomClassName.new(level + 1)
end
5071c5b861341c0dcfcf6ac86327701f

Tien Dung

September 22, 2008, September 22, 2008 01:53, permalink

No rating. Login to rate!

@Adam: cool refactoring :D

E0dabbf83e6c56adc987e069e4b83a2b

pootcode

September 22, 2008, September 22, 2008 19:05, permalink

No rating. Login to rate!

Oh lawd

.-´¯¯¯`-.
,´          `.
|             \
|              \
\           _  \
,\  _    ,´¯,/¯)\
( q \ \,´ ,´ ,´¯)
 `._,)     -´,-´)
   \/         ,´/
    )        / /
   /       ,´-´

Your refactoring





Format Copy from initial code

or Cancel