Ruby: How do I join elements of an array together with a prefix?

前端 未结 1 960
旧时难觅i
旧时难觅i 2021-02-12 14:44

I have an array like so:

[\"marblecake\", \"also\", \"the\", 1337]

I would like to get back a string which contains each element of the array p

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-12 14:56

    If your array is in a then this one-liner will do it

    a.map { |k| "%#{k}" }.join("_")
    

    You could easily put this in a function of your own - even add it to the Array class so that you can call it on an array, like in your example.

    Note that the '!' version of map (map!) will modify the array in place - perhaps not your intent.

    0 讨论(0)
提交回复
热议问题