質問

I need to "translate" the following loop from JavaScript to Ruby:

for(i=0;i<=b.length-1;i++){
  if(!(i%2)){
    c+=b[i]
  }
}

Here is how I tried to write the same in Ruby:

until i == b.length-1 do
  unless i%2 == true
    c += b[i]
    i += 1
  end  
end

The modulus operator in Ruby, however, seems to return false all the time; which renders the whole condition meaningless.

What am I doing wrong?

役に立ちましたか?

解決

You should have:

unless i%2 == 1

or, equivalently:

if i%2 == 0

The reason of unexpected behavior is that Ruby treats all values (including 0) except false and nil as "truthy" in conditional statements.

他のヒント

Both in JavaScript and Ruby the modulus operator is expected to return an integer not a boolean:

2 % 2 
# => 0
3 % 2
# => 1

So, to check if i is even, you have to implement your condition like this:

unless i % 2 != 0
  # ...

However, for the purpose I think it's better to use one of the methods Integer#even? and Integer#odd?:

if i.even?
  #...

In Javascript, 0 and -0 are falsy values and therefore evaluate to false when doing comparisons. All other Numbers evaluate to true.

In Ruby, there is no implicit type conversion when comparing objects, and 0 evaluates to true. If you want to do your comparison in Ruby, you should use

if i%2 == 0

instead of your code.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top