2

I've got a few ideas but wanted to get a few other options. Here is the ugly:

def normal_balance
  if type.to_s == 'Asset' or type.to_s == 'Expense'
    if contra
      "Credit"
    else
      "Debit"
    end
  else
    if contra
      "Debit"
    else
      "Credit"
    end
  end
end
1
  • 2
    What type of value is type? (Why are you calling to_s on it?) Commented Apr 22, 2012 at 15:28

3 Answers 3

2

Not exactly a ruby-specific method, but since you're just inverting a boolean if a value in a given set, you can represent the boolean as a variable and then just use one condition to obtainin the 'debit' or 'credit' string.

def normal_balance
  debit = %w[Asset Expense].include?(type.to_s) ? !contra : contra
  debit ? "Debit" : "Credit"
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Big thing I've taken away here is the ? operator. I remember reading about it but application didn't come to mind.
Yeah, it is a discriminator due to the model using datamapper.
1
%w[Asset Expense].include?(type.to_s) == !!contra ? "Credit" : "Debit"

The !! is just there to force contra into a boolean, so we can compare it using ==. It could also be written as

%w[Asset Expense].include?(type.to_s) ^ contra ? "Debit" : "Credit"

But that's less readable, IMHO.

4 Comments

Thanks. Certainly most concise. Took some reading to refresh my self on a few of the operators.
Isn't ^ going to return the opposite of ==? It's XOR, so true ^ true == false whereas (true == true) == true. Perhaps you meant &?
@Andrew: That's why I swapped the strings. Boolean a ^ b is equivalent to !!a != !!b. & has different semantics, by the way.
@NiklasB. Ahhhh did not see that, my fault.
0
def normal_balance(type,con)
  contra = {:yes => 'Debit'}
  contra.default= 'Credit'
  card_type = {:Asset => contra, :Expense => contra}
  card_type.default = contra

  card_type[type.to_sym][con.to_sym]
end

This is mostly used for replacing if that you use a hash.

I don't know what is the possible value for contra so you should replace that in the first hash.

Actually in your case you only test for contra_type. Maybe you should test that only.

1 Comment

Thanks. I see that now on the original IF statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.