Kirill Zhuravlov
Kirill Zhuravlov

Reputation: 464

DRY integer float converter ruby on rails/ruby

I have NoDataBase calculator app. It takes digit parameters from view, made calculations in controller with some methods and return answer. The issue is to show correct answer in view. I need to show exact float or integer. I made some convertation, but it seems to looks ugly. I wondering, how to implement DRY converter.

Links:

interest_calculator/index.html.erb

interest_calculator_controller.rb

number_to_number spec tests

persent_from_number spec tests

Rounding of float to 10 characters

# If accepted parameter is integer, then it shows in view as 5, when it
# is float, it shows as 5.1  
@first_0   = params[:a_0].to_f % 1 != 0 ? params[:a_0].to_f : params[:a_0].to_i
@second_0  = params[:b_0].to_f % 1 != 0 ? params[:b_0].to_f : params[:b_0].to_i
@first_1   = params[:a_1].to_f % 1 != 0 ? params[:a_1].to_f : params[:a_1].to_i
@second_1  = params[:b_1].to_f % 1 != 0 ? params[:b_1].to_f : params[:b_1].to_i  


integer_decimal_converter(@first_0, @second_0, @first_1, @second_1)

Upvotes: 0

Views: 162

Answers (1)

Bartosz Bonisławski
Bartosz Bonisławski

Reputation: 247

If you don't need global variables you can do something like this:

result = [:a_0, :b_0, :a_1, :b_1].map do |key|
  value = params[key].to_f
  value % 1 == 0 ? value.to_i : value
end

integer_decimal_converter(*result)

Upvotes: 1

Related Questions