I have a formula in JS that uses the bitwise NOT operator.
~~(n/m + 0.5) * m;
How do I write the same expression in ruby? There is no bitwise NOT operator in ruby.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I believe the same expression in Ruby would be
(n/m + 0.5).to_i * m, or, alternatively,Integer(n/m + 0.5) * m.It looks like the doubled bitwise complement there is really being used to truncate the decimal part of the calculation, in order to compute the nearest n such that n is a multiple of m. (In another language, I would say “convert to integer”, but Javascript has a unified arithmetic type.)
Update: Mladen Jablanović suggests a cast, and yes, if both m and n are Fixnum, it’s needed. In Ruby 1 / 3 is 0 but in JS it’s 0.333… Here is a refined suggestion: