简体   繁体   中英

Take out values from hash and insert in an array in ruby

I am having

students = {1=>"alexandar", 2=>"mona", 3=>"gaga", 4=>"", 5=>"tom", 35=>"abcd", 44=>"hin"}
array = []

I had given this

array = students.values

and when I write in my test.js.erb

$('.show-test').text('<%= array%>')

it gives o/p

[&quot;alexandar&quot;, &quot;mona&quot;, &quot;gaga&quot;,
&quot;tom&quot;, &quot;abcd&quot;, &quot;hin&quot;]

Now I need to show text like this

 [alexander, mona, gaga, tom, abcd, hin]

Please guide me how to solve this. Thanks in advance

Super simple, use Hash#values :

$> students = {1=>"alexandar", 2=>"mona", 3=>"gaga", 4=>"", 5=>..............}
$> students.values # <- Array with values
=> ["alexandar", "mona", "gaga", "", "tom", "abcd", "hin"]

Update:

Use html_safe if you trying to render json from controller.

$('.show-test').text('<%= array.html_safe %>') 

or:

$('.show-test').text('<%= array.to_json.html_safe %>')

or (the same thing as html_safe ):

$('.show-test').text('<%= raw(array.to_json) %>')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM