1

I'm wondering about something in a project of mine with OpalRB (the Ruby-to-JavaScript compiler): when you make a constant in Opal, like so:

ONE = 1

... is that essentially the same thing as saying this is JavaScript?:

const ONE = 1;

The reason that I ask this question is that the const keyword in JS in not always properly supported in each browser and, due to that, I'm somewhat wary about using constants with Opal.

GDP2
  • 1,948
  • 2
  • 22
  • 38

1 Answers1

1

... is that essentially the same thing as saying this is JavaScript?

No it's not. const in JavaScript makes a variable that ignores any re-assignments and keeps its original value. In Ruby, constants complain with a warning when re-assigned, but actually do get re-assigned.

Here is how ONE=1 in Ruby gets compiled by Opal:

$opal.cdecl($scope, 'ONE', 1);

As you can see, constants aren't stored as variables the way local variables are, they're stored internally inside the scope object.

The cdecl function can do whatever it wants if ONE is already declared. The developers of Opal however, seemed to choose to not show a warning when constants are reassigned. Try this (it's always fun to play around with this webpage and see how the compiler works).

Therefore, constants in Opal-compiled Ruby aren't.

itdoesntwork
  • 4,666
  • 3
  • 25
  • 38
  • Thanks, this made a lot of sense. – GDP2 Sep 07 '14 at 23:06
  • Or, to put it more succinctly: you cannot compile a Ruby constant to an ECMAScript constant because they have completely different semantics. – Jörg W Mittag Sep 08 '14 at 09:57
  • Interestingly, however, Ruby strings are compiled to ECMAScript strings, even though they are completely different (Ruby strings are mutable, ECMAScript strings are immutable). – Jörg W Mittag Sep 08 '14 at 09:59
  • 1
    I feel like Opal isn't meant to be a platform to run already-existing Ruby apps in the browser, but to allow people to code for the browser in Ruby. Maybe this is why strings are not tampered with when converting code. – itdoesntwork Sep 14 '14 at 16:10