Extract a part of a string with Ruby

What to do in this article

In this article, I will explain how to extract an arbitrary character string in Ruby. It also explains the behavior when a negative number is specified as an argument when extracting a character string.

To retrieve a string

The code itself looks like this: By specifying the 0th to 2nd characters in the character string, the 3rd character from the beginning is output.

def left2(str)
  puts str[0..2]
end

left2('Hello')

--Execution result--
Hel

Now let's set the second argument of str to -1.

def left2(str)
  puts str[0..-1]
end

left2('Hello')

--Execution result--
Hello

All the characters were taken out and it was output as Hello. The reason is that -1 represents the end of the string. This is the result because we are extracting from the 0th to the end of the string. The table shows which character each character corresponds to.

letter For positive numbers For negative numbers
H 0th character -5th character
e 1st character −4th character
l 2nd character -3rd character
l 3rd character −2nd character
o 4th character -1st character

According to the table above, if you set the first argument to 1 and the second argument to -4, Since the 0th and 1st characters are extracted, the result is assumed to be "He". Let's do it right away.

def left2(str)
  puts str[0..-4]
end

left2('Hello')

·Execution result

% ruby test.rb
He

It became "He" as expected. The point of this article is that negative values can be used as arguments when retrieving strings.

Recommended Posts

Extract a part of a string with Ruby
Extract a string starting with a capital letter with a regular expression (Ruby)
Count the number of occurrences of a string in Ruby
Let's make a LINE Bot with Ruby + Sinatra --Part 2
Ruby Learning # 8 Working With String
Let's make a LINE Bot with Ruby + Sinatra --Part 1
Cut out a Ruby string
[Java] Cut out a part of the character string with Matcher and regular expression
The nth and n + 1st characters of a Ruby string
Install Ruby 3.0.0 Preview 1 with a combination of Homebrew and rbenv
Impressions of making BlackJack-cli with Ruby
Make a typing game with ruby
[Illustration] Finding the sum of coins with a recursive function [Ruby]
Make a note of Ruby keyword arguments
part of the syntax of ruby ​​on rails
Let's make a smart home with Ruby!
I made a risky die with Ruby
Split a string with ". (Dot)" in Java
Read a string in a PDF file with Java
AtCoder Beginner Contest 169 A, B, C with ruby
Created a native extension of Ruby with Rust and published it as a gem
[Ruby] Arguments with keywords and default values of arguments
Creating a browser automation tool with Ruby + Selenium
[Delete the first letter of the character string] Ruby
<Java> Quiz to batch convert file names separated by a specific character string with a part of the file name
Get a list of Qiita articles for a specific user with Ruby + Qiita API v2
[Java] The confusing part of String and StringBuilder
Manage the version of Ruby itself with rbenv
Convert a string to a character-by-character array with swift
Basics of Ruby
[Ruby on Rails] A memorandum of layout templates
Get Body part of HttpResponse with Filter of Spring
[Ruby] How to generate a random alphabet string
[Ruby / Rails] Inactivate Lint of update_all with Rubocop
I checked the number of taxis with Ruby
Create a native extension of Ruby in Rust
I made a portfolio with Ruby On Rails
Write a test by implementing the story of Mr. Nabeats in the world with ruby
Extract elements by doing regular expression replacement from a lot of HTML with java
[Ruby] Cut out a string using the slice method
Create a Jar file with two lines of command
A quick review of Java learned in class part4
Play down with Raspberry PI4 as a server. Part 2
[Ruby] Generate a concatenated QR code with rqrcode (Knowledge)
The story of making a reverse proxy with ProxyServlet
[Ruby] I made a crawler with anemone and nokogiri.
Build ruby debug environment with VS Code of Windows 10
[Ruby] Generate a concatenated QR code with rqrcode (Practice)
A quick review of Java learned in class part3
Ruby Regular Expression Extracts from a specific string to a string
Extract a specific element from the list of objects
A quick review of Java learned in class part2
Why implement with a singleton instead of a static method
Use Coveralls with GitHub Actions in a Ruby repository
Replace only part of the URL host with java
Extract all data about a particular user with ActiveRecord
Build a WEB system with Spring + Doma + H2DB Part 2
Install Ruby 3.0.0 with asdf
[Ruby] Get in the habit of using the dup method when making a copy of a string variable
Introduction of Docker --Part 1--
SaveAsBinaryFile with Spark (Part 2)