Ruby 中的字符串连接 [英] String concatenation in Ruby

查看:53
本文介绍了Ruby 中的字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 Ruby 中连接字符串的更优雅的方法.

I am looking for a more elegant way of concatenating strings in Ruby.

我有以下几行:

source = "#{ROOT_DIR}/" << project << "/App.config"

有没有更好的方法来做到这一点?

Is there a nicer way of doing this?

那么,<<+ 之间有什么区别?

And for that matter what is the difference between << and +?

推荐答案

您可以通过多种方式做到这一点:

You can do that in several ways:

  1. 正如你用 << 展示的那样,但这不是通常的方式
  2. 带字符串插值

  1. As you shown with << but that is not the usual way
  2. With string interpolation

source = "#{ROOT_DIR}/#{project}/App.config"

  • +

    source = "#{ROOT_DIR}/" + project + "/App.config"
    

  • 从我所看到的(虽然没有测量),第二种方法在内存/速度方面似乎更有效.当 ROOT_DIR 为 nil 时,这三种方法都会抛出未初始化的常量错误.

    The second method seems to be more efficient in term of memory/speed from what I've seen (not measured though). All three methods will throw an uninitialized constant error when ROOT_DIR is nil.

    在处理路径名时,您可能需要使用 File.join 以避免弄乱路径名分隔符.

    When dealing with pathnames, you may want to use File.join to avoid messing up with pathname separator.

    归根结底,这是一个品味问题.

    In the end, it is a matter of taste.

    这篇关于Ruby 中的字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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