0

I have a ruby code that will generate an array.I need to use that array in javascript.

<%= region.zip(min, max).select {|_, a, b| a == '0' && b == '0'}.map(&:first)%>;

This above code will generate an array like this

["A", "B", "C", "F", "H"]

Here is the demo http://repl.it/t03/680

I want to use this array in javascript. Below is what I tried and the error I got in console.

<script>

 var output = <%= (region.zip(min, max).select {|_, a, b| a == '0' && b == '0'}.map(&:first)).gsub('"', '') %>;

</script>

Error is

SyntaxError: expected expression, got '&'

var output = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;F

Thanks

3 Answers 3

1

JSON is technically valid Javascript, so you could do something like:

 var output = <%= (region.zip(min, max).select {|_, a, b| a == '0' && b == '0'}.map(&:first)).map{|item| item.gsub('"', '')}.to_json %>;

And that should work as expected.

Note: I added the .to_json at the end of the Ruby code.

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

6 Comments

I tried ..got this error undefined method `gsub' for ["A", "B", "C", "F", "H"]:Array
Try removing the gsub(...). I think this is not actually needed.
Alternately, if your strings still have quotes in them you'd like to remove, you could run gsub inside another map. The reason you can't gsub on the whole array is because gsub can only be called on individual strings. So maybe you instead want to do something like ...).map{|item| item.gsub('"', '') }
sorry..updated solution dint work..getting the original error
Ok, well then if all else fails, you can try wrapping the whole thing in raw(...) which should stop it from escaping the quotes. var output = <%= raw((regi...', '')}.to_json) %>;
|
1

I used to do in the "standard" way, writing JS storing JSON in a variable, now I highly recommend to use: gon

It's great and allows you to handle with this situation easily, in your controller type:

gon.push({variable_name: [1,2,3]})

In your app layout use:

<%= include_gon %>
<!-- include your action js code -->

In your js you can just type:

console.log(gon.variable_name) // [1,2,3]

Comments

0

This is actually jeremy answer after modification.

 var output = <%= raw(region.zip(min, max).select {|_, a, b| a == '0' && b == '0'}.map(&:first).map{|item| item.gsub('"', '')}.to_json) %>

Comments

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.