Ruby Greed Koan - How can I improve my if/then soup?
Looks OK. I might have written some things slightly differently, say:
def do_triples number, total
total + (number == 1 ? 1000 : number * 100)
end
If you want to do something that few languages other than Ruby can do, I suppose the following might be justifiable under DIE and DRY, on alternate Tuesdays, but I don't think those Ruby maxims were really intended to apply to common subexpression elimination. Anyway:
def do_triples number, total
total +
if number == 1
1000
else
number * 100
end
end
def do_triples number, total
if number == 1
1000
else
number * 100
end + total
end
Ruby Greed Koan - How can I improve my if/then soup?
Looks OK. I might have written some things slightly differently, say:
def do_triples number, total
total + (number == 1 ? 1000 : number * 100)
end
If you want to do something that few languages other than Ruby can do, I suppose the following might be justifiable under DIE and DRY, on alternate Tuesdays, but I don't think those Ruby maxims were really intended to apply to common subexpression elimination. Anyway:
def do_triples number, total
total +
if number == 1
1000
else
number * 100
end
end
def do_triples number, total
if number == 1
1000
else
number * 100
end + total
end
Ruby Koans 182. Refactor help
I've put up a walkthrough of refactorings at https://gist.github.com/1091265. Final solution looks like:
def score(dice)
(1..6).collect do |roll|
roll_count = dice.count(roll)
case roll
when 1 : 1000 * (roll_count / 3) + 100 * (roll_count % 3)
when 5 : 500 * (roll_count / 3) + 50 * (roll_count % 3)
else 100 * roll * (roll_count / 3)
end
end.reduce(0) {|sum, n| sum + n}
end
note:.reduce
is a synonym for .inject
How to reject arrays with unwanted number range
Use Enumerable#all?
dice.all? {|num| (1..6).include? num}
Related Topics
How to List the Currently Available Objects in the Current Scope in Ruby
Read Input from Console in Ruby
When to Use Struct Instead of Hash in Ruby
Installing Ruby 1.9.1 on Ubuntu
Attr_Accessor on Class Variables
Installing the Postgresql Gem with 'Gem Pq' Fails with Error: Failed to Build Gem Native Extension
Ruby Way to Generate a Hmac-Sha1 Signature for Oauth
Find or Create Record Through Factory_Girl Association
Should I Define a Main Method in My Ruby Scripts
How to Convert a JSON Formatted Key Value Pair to Ruby Hash with Symbol as Key
Ruby - Can't Modify Frozen String (Typeerror)
Can't Install Ffi -V '1.9.18' on MACos Catalina