80

文字列の最初の100文字などを選択するための関数を見つけようとしています。PHPには、substr関数があります

Rubyには同様の機能がありますか?

4

2 に答える 2

152

試してみてくださいfoo[0...100]、どんな範囲でもかまいません。範囲も負になる可能性があります。これはRubyのドキュメントで詳しく説明されています。

于 2011-06-21T10:43:26.233 に答える
45

[]-operator(docs )の使用:

foo[0, 100]  # Get 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!)

Ruby 2.7のアップデート最初の範囲は現在(2019-12-25現在)ここにあり、おそらく「配列の最初のxxを返す」の標準的な答えです:

foo[...100]  # Get all chars from the beginning up until the 100th (exclusive)

メソッドの使用.sliceドキュメント):

foo.slice(0, 100)  # Get 100 characters starting at position 0
foo.slice(0...100) # Behaves the same as operator [] 

そして完全を期すために:

foo[0]         # Returns the indexed character, the first in this case
foo[-100, 100] # Get 100 characters starting at position -100
               # Negative indices are counted from the end of the string/array
               # Caution: Negative indices are 1-based, the last element is -1
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

Ruby 2.6のアップデート無限の範囲がここにあります(2018-12-25現在)!

foo[0..]      # Get all chars starting at the first. Identical to foo[0..-1]
foo[-100..]   # Get the last 100 characters
于 2016-01-24T09:46:56.797 に答える