Ruby:字符串不再在1.9中混入Enumerable [英] Ruby: String no longer mixes in Enumerable in 1.9

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

问题描述

所以我怎么仍然可以编写漂亮的代码,例如:

So how can I still be able to write beautiful code such as:

'im a string meing!'.pop

注意: str.chop 不是足够的答案

推荐答案

这不是可枚举的字符串通常会枚举的内容。是一个字符串,由...

It is not what an enumerable string atually enumerates. Is a string a sequence of ...


  • 行,

  • 字符,

  • 代码点还是

  • 字节?

  • lines,
  • characters,
  • codepoints or
  • bytes?

答案是:全部其中的任何一个,取决于上下文,可以是其中一个,也可以不是。因此,必须告诉Ruby真正想要的是哪个。

The answer is: all of those, any of those, either of those or neither of those, depending on the context. Therefore, you have to tell Ruby which of those you actually want.

String 类中有几种方法返回上面任何一个的枚举数。如果您想要1.9之前的行为,您的代码示例将是

There are several methods in the String class which return enumerators for any of the above. If you want the pre-1.9 behavior, your code sample would be

'im a string meing!'.bytes.to_a.pop

这看起来有些丑陋,但这是有原因的:字符串是一个序列。您将其视为堆栈。堆栈不是序列,实际上它是序列的相反

This looks kind of ugly, but there is a reason for it: a string is a sequence. You are treating it as a stack. A stack is not a sequence, in fact it pretty much is the opposite of a sequence.

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

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