Ruby Greed Koan - How to Improve My If/Then Soup

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



Leave a reply



Submit