Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - How to select some characters from string

I am trying to find a function for select e.g. first 100 chars of the string. In PHP, there exists the substr function

Does Ruby have some similar function?

like image 378
user1946705 Avatar asked Jun 21 '11 10:06

user1946705


People also ask

How do you access characters in a string in Ruby?

Accessing Characters Within a String You can also access a single character from the end of the string with a negative index. -1 would let you access the last character of the string, -2 would access the second-to-last, and so on. This can be useful for manipulating or transforming the characters in the string.

How do I remove a specific character from a string in Ruby?

In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.

How do you get the first two characters of a string in Ruby?

To access the first n characters of a string in ruby, we can use the square brackets syntax [] by passing the start index and length. In the example above, we have passed the [0, 3] to it. so it starts the extraction at index position 0 , and extracts before the position 3 .


1 Answers

Try foo[0...100], any range will do. Ranges can also go negative. It is well explained in the documentation of Ruby.

like image 87
Miki Avatar answered Oct 11 '22 18:10

Miki