Matz为什么选择在Ruby中默认使字符串可变? [英] Why did Matz choose to make Strings mutable by default in Ruby?

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

问题描述

与该问题相反:为什么不能字符串在Java和.NET中是可变的?

在Ruby中做出此选择仅仅是因为操作(追加等)对可变字符串有效,还是有其他原因?

Was this choice made in Ruby only because operations (appends and such) are efficient on mutable strings, or was there some other reason?

(如果仅是效率,那似乎很奇怪,因为Ruby的设计似乎并没有在促进高效实现上给予很高的重视.)

(If it's only efficiency, that would seem peculiar, since the design of Ruby seems otherwise to not put a high premium on faciliating efficient implementation.)

推荐答案

这符合Ruby的设计.不可变的字符串比可变的字符串更有效-重复使用字符串时,复制较少-但使程序员的工作更加困难.将字符串视为可变的很直观-您可以将它们连接在一起.为了解决这个问题,Java悄悄地将两个字符串的连接(通过+转换为使用StringBuffer对象),并且我敢肯定还有其他此类黑客. Ruby选择默认情况下使字符串可变,但会降低性能.

This is in line with Ruby's design, as you note. Immutable strings are more efficient than mutable strings - less copying, as strings are re-used - but make work harder for the programmer. It is intuitive to see strings as mutable - you can concatenate them together. To deal with this, Java silently translates concatenation (via +) of two strings into the use of a StringBuffer object, and I'm sure there are other such hacks. Ruby chooses instead to make strings mutable by default at the expense of performance.

Ruby还具有许多破坏性方法,例如String#upcase!,它们依赖于可变的字符串.

Ruby also has a number of destructive methods such as String#upcase! that rely on strings being mutable.

另一个可能的原因是Ruby受Perl启发,而Perl恰好使用可变字符串.

Another possible reason is that Ruby is inspired by Perl, and Perl happens to use mutable strings.

Ruby具有符号和冻结的字符串,两者都是不可变的.另外,保证符号在每个可能的字符串值中都是唯一的.

Ruby has Symbols and frozen Strings, both are immutable. As an added bonus, symbols are guaranteed to be unique per possible string value.

这篇关于Matz为什么选择在Ruby中默认使字符串可变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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