0

Below is a piece of Ruby code I am rewriting in JavaScript. I understand that it packs the array as '8-bit unsigned (unsigned char)', and then unpacks it as '16-bit unsigned, VAX (little-endian) byte order', but my attempts to make it work in JavaScript have failed.

I was wondering if the ||= has any impact on the values in the array?

I would also like to know how the packing and unpacking influences the values in the array? Does it only change 0x01 into 0x0100?

@_tree_left ||= [
 0x01, 0x01, 0x03, 0x01, 0x05, 0x01, 0x07, 0x01, 0x0B, 0x01, 0x0D, 0x01,
 0xF9, 0x00, 0xFB, 0x00, 0xFD, 0x00, 0x00, 0x01
].pack('C*').unpack('v*')
the Tin Man
161k44 gold badges222 silver badges308 bronze badges
asked Apr 4, 2013 at 16:32

2 Answers 2

2

||= is a classic Ruby idiom meaning:

v = v || second_expression

If the first expression evaluates to false or nil it means second one will be executed.

the Tin Man
161k44 gold badges222 silver badges308 bronze badges
answered Apr 4, 2013 at 16:42
Sign up to request clarification or add additional context in comments.

Comments

1

The ||= is just shorthand for:

@_tree_left = @_tree_left || [ ... ].pack('C*').unpack('v*')

The first time the statement is executed, @_tree_left will be nil, and so it will be assigned the value of the right hand expression. If executed a second time, then as long as @_tree_left has any kind of a value left, it will not be changed.

It's a bit easier to see if simplified.

@a # => nil
@a = @a || 123 # => 123
@a = @a || 456 # => 123, no change this time

The rest of the expression is storing and retrieving a specific binary string.

It can be easily duplicated in JavaScript. It's just combining every two values in the array. So it's computing:

b[0] = a[0] + (a[1] << 8)
b[1] = a[2] + (a[3] << 8)
. . .
answered Apr 4, 2013 at 16:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.