48
A
回答
95
尝试foo[0...100]
,任何范围都可以。范围也可以消极。 Ruby的well explained in the documentation。
16
使用[] - 运算符:
foo[0,100] # Get the first 100 characters starting at position 0
foo[0..99] # Get all characters in index range 0 to 99 (inclusive)
foo[0...100] # Get all characters in index range 0 to 100 (exclusive)
使用.slice方法:
foo.slice(0, 100) # Get the first 100 characters starting at position 0
foo.slice(0...100) # All identical to []
并且为了完整性:
foo[0] # Returns the first character (doh!)
foo[-100,100] # Get the last 100 characters in order. Negative index is 1-based
foo[-100..-1] # Get the last 100 characters in order
foo[-1..-100] # Get the last 100 characters in reverse order
foo[-100...foo.length] # No index for one beyond last character
+0
谢谢你。用[]运算符看到不同的细微差别是有帮助的,而不仅仅是正确的答案。 – johngraham
+0
这就是我们如何喜欢我们的Ruby。不只是一个正确的做法(TM)。 –
相关问题
- 1. 红宝石:字符从字符串
- 2. 如何从红宝石字符串中提取子字符串?
- 3. 从字符串中提取 - 红宝石
- 4. 红宝石 - 从字符串中删除
- 5. 红宝石GSUB字符串
- 6. 红宝石ZEROFILL字符串
- 7. gsub从红宝石中的字符串中的ASCII码字符
- 8. 红宝石 - 用另一个字符串
- 9. 获取字符串数组从纯字符串红宝石
- 10. 字符串文字的红宝石'OR'
- 11. 红宝石字符串 - 检查一组字符串匹配
- 12. 红宝石从字符串中删除第一个字
- 13. 从一开始就选择一个字符串的一个子红宝石
- 14. 如何从红宝石中的字符串中删除短语?
- 15. 比较字符串在红宝石中的字符串出错
- 16. 红宝石 - 从字符串获得第n个字符
- 17. 从字符串的末尾删除字符到红宝石中的字符
- 18. 在轨道上的红宝石替换一些字符串
- 19. 红宝石拆分字符串
- 20. 红宝石字符串连接
- 21. 红宝石推字符串数组
- 22. 字符串类在红宝石
- 23. 转换红宝石字符串BIGNUM
- 24. 红宝石 - 字符串内的评估
- 25. 红宝石:字符串比较问题
- 26. 红宝石to_yaml UTF8字符串
- 27. 红宝石比较字符串
- 28. 红宝石字符串散列值
- 29. 红宝石散列字符串插值
- 30. 字符串操作红宝石图案
foo的[0100]是相同的。 – steenslag
还要注意'''foo [0..100]''''和''foo [0 ... 100]'''是不同的。一个是零到一百,而另一个是零到九十九。 –
以上澄清:foo [0..100]是_inclusive_(0到100),foo [0 ... 100]是_exclusive_(0到99) – OneHoopyFrood