数组 * 字符串在 Ruby 中是什么意思? [英] What does array * string mean in Ruby?

查看:48
本文介绍了数组 * 字符串在 Ruby 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在浏览一些 Rails 源代码时遇到了

I was looking through some Rails source code and came across

# File vendor/rails/activesupport/lib/active_support/vendor/builder-2.1.2/builder/css.rb, line 129
129:     def target!
130:       @target * ''
131:     end

* '' 有什么作用?乘以一个空字符串......?你为什么要这样做.

What does the * '' do? Is that multiplication by an empty string...? And why would you do that.

推荐答案

这是一个奇怪的语法.这些是等效的:

This is a bizarre syntax. These are equivalent:

>> [1, 2, 3] * 'joiner'
=> "1joiner2joiner3"

>> [1, 2, 3].join 'joiner'
=> "1joiner2joiner3"

所以在这种情况下,它将 @target 的所有条目连接成一个字符串,条目之间没有任何内容.

so in this case it joins all the entries of @target into one string, with nothing between the entries.

注意:如果您执行类似 [1, 2, 3] * 3 的操作(使用 int 而不是 str),你会得到数组的三个串联副本.

Note: if you do something like [1, 2, 3] * 3 (using an int instead of a str), you'll get three concatenated copies of the array instead.

这篇关于数组 * 字符串在 Ruby 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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