Tutorial :Ruby: Forcing an Integer (Fixnum/Bignum) over Boolean



Question:

I have an integer that is initially 0 and, after calculations, often ends up between 0 - 99. The problem is that since early on in the game, it calculates out to 0 or 1 often, it gets assigned as a TrueClass or FalseClass instead of a numerical value, which messes up a future x > 0 comparison. Is there a built-in Ruby way to force the variable into being a Fixnum/Integer type or will I have to monkeypatch it?

Here is the code it applies to:

Step 10: Compute the Target's Magic Defense Multiplier

mdef_multi = self.mdef_multi    # Step 11: Modify the Magic Defense Multiplier  # If Toad  mdef_multi = 0 if user.states.include?(11)  # If Charging  mdef_multi = 0 if user.states.include?(30)  # If cast on self or PC onto PC  # 0 if PC targetting PC  mdef_multi = self.is_a?(Game_Actor) and user.is_a?(Game_Actor) ? 0 : mdef_multi  # 99 MDef Multi if max MDef  mdef_multi = self.is_a?(Game_Enemy) and mdef == 255 ? 99 : mdef_multi  # If Solo Multiplier is enabled  mdef_multi = obj.element_set.include?(26) ? 1 : mdef_multi    # Step 12: Modify the Spell Multiplier  hits = 0, missed = 0, evaded = 0  while spl_multi > 0    spl_multi -= 1    if rand(99) <= hit      if mdef_multi > 0  

The last line is where I run into the variable-type issue. It's technically RGSS2 from RPG Maker VX. And please excuse my horrid commenting and coding style.


Solution:1

First of all, Ruby doesn't auto-convert things, so your integer isn't getting converted to a boolean because it's 0 or 1.

Instead, what's happening is the line

mdef_multi = self.is_a?(Game_Actor) and user.is_a?(Game_Actor) ? 0 : mdef_multi  

is being parsed as

( mdef_multi = self.is_a?(Game_Actor) ) and user.is_a?(Game_Actor) ? 0 : mdef_multi  

because of the way and works. Basically = has higher precendence than and, so the variable is only being set to the result before the and, which is a true/false value. && has a higher precedence than = though, so using && here should work. For this reason, some Ruby programmers recommend only using &&, never and. See http://blog.jayfields.com/2007/08/ruby-operator-precedence-of-and-which.html for more explanation.

If you use && instead of and on this line and the next one, it should fix the problem.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »