Ruby:如何将数组元素与前缀连接在一起? [英] Ruby: How do I join elements of an array together with a prefix?

查看:150
本文介绍了Ruby:如何将数组元素与前缀连接在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

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 prefixed by some specified string, then joined together by another specified string. For example,

["marblecake", "also", "the", 1337].join_with_prefix("%", "__")

应该导致

# => %marblecake__%also__%the__%1337

我该怎么办?

推荐答案

如果您的数组位于a中,则此一线式即可做到

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

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

您可以轻松地将其放在自己的函数中-甚至可以将其添加到Array类中,以便可以像在示例中一样在数组上调用它.

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.

请注意,!"版本的地图(map!)将在适当的位置修改数组-也许不是您的意图.

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

这篇关于Ruby:如何将数组元素与前缀连接在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆