2

In a block of C++ code, I saw something like this:

enum {
  a = 0,
  b = (1U << 0),
  c = (1U << 1),
  d = (1U << 2)
}

To achieve the same thing in Ruby, would I have to do something like this?

d = "1U".bytes.inject { |x,y| (x<<8) | y } << 2

Or would I need to do something else to accomplish what the C++ code does?

1 Answer 1

2

1U in the C++ is not a string, it is the unsigned number 1. In fact, the code above in C++ could be substituted by:

a = 0;
b = 1U;
c = 2U;
d = 4U;

In ruby you can simply do

> 1 << 0
 => 1 #0001
> 1 << 1
 => 2 #0010
> 1 << 2
 => 4 #0100

But you are not using bytewise operations in ruby unless you have a very good reason for it, right? :-)

Sign up to request clarification or add additional context in comments.

1 Comment

Ah okay, thanks! I'm taking some C++ code and converting it into Ruby but that bit (pun not intended) messed me up since I don't really program in C++ and don't see that representation of values.

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.