Ruby中的字符串可变吗? [英] Are strings in Ruby mutable?

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

问题描述

考虑以下代码:

$ irb
> s = "asd"
> s.object_id   # prints 2171223360
> s[0] = ?z     # s is now "zsd"
> s.object_id   # prints 2171223360 (same as before)
> s += "hello"  # s is now "zsdhello"
> s.object_id   # prints 2171224560 (now it's different)

似乎无需创建新字符串即可更改单个字符.但是,在字符串后面附加显然会创建一个新字符串.

Seems like individual characters can be changed w/o creating a new string. However appending to the string apparently creates a new string.

Ruby中的字符串可变吗?

推荐答案

是的,与Python不同,Ruby中的字符串是可变的.

Yes, strings in Ruby, unlike in Python, are mutable.

s += "hello"不是,将"hello"附加到s-创建了一个全新的字符串对象.要附加到字符串就地",请使用<<,例如:

s += "hello" is not appending "hello" to s - an entirely new string object gets created. To append to a string 'in place', use <<, like in:

s = "hello"
s << "   world"
s # hello world

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

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