简单但令人困惑的Ruby字符串操作

时间:2010-02-06 18:38:01

标签: php ruby string

我正在尝试将一小部分Ruby转换为PHP,到目前为止我已经取得了成功,除了这一行:

string = string[16,string.length-16]

我在PHP中试过这两件事:

$string = substr($string, 16, strlen($string) - 16);
// and
$string = substr($string, 16, strlen($string) - 32);

但问题是我不知道string[#,#]语法的作用。我之前见过string[#..#]string[#],但从未见过string[#,#]

4 个答案:

答案 0 :(得分:3)

string[x,y]是一个子索引,从索引x开始,是y个字符(或1.8个字节)长(与string[x..y]相反,它从索引x开始,在索引y处停止)。

答案 1 :(得分:3)

我觉得$string = substr($string, 16, strlen($string) - 16);必须工作......不同的输出?

哦,还有更多关于红宝石中的字符串: http://ruby-doc.org/core/classes/String.html#M000771

答案 2 :(得分:2)

如果你看一下Ruby文档,你会学到各种奇怪的东西。但是那个语法只是子串和偏移量,所以如果你只是启动一个irb并且有点蠢蠢欲动

>> "123456789"[3,2]
=> "45"

所以你可以看到发生了什么。无论如何,文档are here

str.index(substring [, offset]) => fixnum or nil
str.index(fixnum [, offset]) => fixnum or nil
str.index(regexp [, offset]) => fixnum or nil
Returns the index of the first occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

   "hello".index('e')             #=> 1
   "hello".index('lo')            #=> 3
   "hello".index('a')             #=> nil
   "hello".index(101)             #=> 1
   "hello".index(/[aeiou]/, -3)   #=> 4

答案 3 :(得分:1)

从回复和你的评论来看,我感觉你的错误在其他地方。也许$ string是空的。通过打印出所有“明显”的东西来测试你的假设。字符串,strlen()等的结果。另外,前一行的错误(例如未终止的if())可能会产生意外结果。