Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a substring in Ruby by x number of chars

Tags:

ruby

I'm trying to produce some Ruby code that will take a string and return a new one, with a number x number of characters removed from its end - these can be actual letters, numbers, spaces etc.

Ex: given the following string

a_string = "a1wer4zx"

I need a simple way to get the same string, minus - say - the 3 last characters. In the case above, that would be "a1wer". The way I'm doing it right now seems very convoluted:

an_array = a_string.split(//,(a_string.length-2)) an_array.pop new_string = an_array.join 

Any ideas?

like image 367
wotaskd Avatar asked Dec 24 '10 19:12

wotaskd


People also ask

How do you extract a substring in Ruby?

the Substring Method in RubyThere is no substring method in Ruby, and hence we rely upon ranges and expressions. If we want to use the range, we have to use periods between the starting and ending index of the substring to get a new substring from the main string.

How do you find the part of a string in Ruby?

A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.

How do you get the first 3 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 .

What is chars method in Ruby?

chars is a String class method in Ruby which is used to return an array of characters in str. Syntax: str.chars. Parameters: Here, str is the given string. Returns: An array of the characters.


1 Answers

How about this?

s[0, s.length - 3] 

Or this

s[0..-4] 

edit

s = "abcdefghi" puts s[0, s.length - 3]  # => abcdef puts s[0..-4]            # => abcdef 
like image 90
Nikita Rybak Avatar answered Sep 28 '22 05:09

Nikita Rybak