سؤال

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?

هل كانت مفيدة؟

المحلول

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? :-)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top