Решение на Първа задача от Здравко Андонов

Обратно към всички решения

Към профила на Здравко Андонов

Резултати

  • 6 точки от тестове
  • 0 бонус точки
  • 6 точки общо
  • 8 успешни тест(а)
  • 0 неуспешни тест(а)

Код

def convert_to_bgn(price, currency)
case currency
when :bgn then price.round(2)
when :usd then (price * 1.7408).round(2)
when :eur then (price * 1.9557).round(2)
when :gbp then (price * 2.6415).round(2)
end
end
def compare_prices(first_price, first_currency, second_price, second_currency)
first_price_bgn = convert_to_bgn(first_price, first_currency)
second_price_bgn = convert_to_bgn(second_price, second_currency)
first_price_bgn <=> second_price_bgn
end

Лог от изпълнението

........

Finished in 0.00633 seconds
8 examples, 0 failures

История (2 версии и 1 коментар)

Здравко обнови решението на 08.10.2015 22:40 (преди над 8 години)

+def convert_to_bgn(price, currency)
+ case
+ when currency == :bgn
+ price.round(2)
+ when currency == :usd
+ (price * 1.7408).round(2)
+ when currency == :eur
+ (price * 1.9557).round(2)
+ when currency == :gbp
+ (price * 2.6415).round(2)
+ end
+end
+
+def compare_prices(first_price, first_currency, second_price, second_currency)
+ first_price_bgn = convert_to_bgn(first_price, first_currency)
+ second_price_bgn = convert_to_bgn(second_price, second_currency)
+ first_price_bgn <=> second_price_bgn
+end

Като цяло добре. Няколко неща:

  • Можеш да "switch"-ваш по currency, вместо да проверяваш с == на всеки ред
  • Използвай едноредовата версия на case (when condition then value)
  • Добре е да отделяш различните смислови компоненти в методите си с нов ред. Например в compare_prices, първите два реда са някакъв вид processing, докато последният е връщане на стойност

Ако имаш желание, можеш да помислиш за алтернативно решение, така че да не ти се налага да повтаряш price и round(2) за всяка валута.

Здравко обнови решението на 09.10.2015 10:46 (преди над 8 години)

def convert_to_bgn(price, currency)
- case
- when currency == :bgn
- price.round(2)
- when currency == :usd
- (price * 1.7408).round(2)
- when currency == :eur
- (price * 1.9557).round(2)
- when currency == :gbp
- (price * 2.6415).round(2)
+ case currency
+ when :bgn then price.round(2)
+ when :usd then (price * 1.7408).round(2)
+ when :eur then (price * 1.9557).round(2)
+ when :gbp then (price * 2.6415).round(2)
end
end
def compare_prices(first_price, first_currency, second_price, second_currency)
first_price_bgn = convert_to_bgn(first_price, first_currency)
second_price_bgn = convert_to_bgn(second_price, second_currency)
+
first_price_bgn <=> second_price_bgn
end