Delete any string

Erase the nth character for any string and I would like to create a method that outputs the erased string.

How to call the method

missing_char(string, num)

I would like to call it with. As an output example

missing_char('kitten', 1)
 => itten
missing_char('kitten', 2)
 => ktten
missing_char('kitten', 4)
 =>kiten

I want to output like this.

You can use the slice method to retrieve the specified element from an array or string. Example)

string = "hoge"

str = string.slice(1)

#Output the character string assigned to str
puts str
#=>"o"

#In the slice method, the character string is output as it is
puts string
#=>"hoge"

We will describe it using the slice method.

First, create the missing_char method. Set the formal argument to (string, num).

def missing_char(string, num)
  string.slice(num - 1)
  puts string
#to string"hoge",2 is passed to num, but the original string doesn't change
#=>hoge
end

In this description, the specified element can be extracted from any character string, but even if the character string is output, there is no change.

So use the slice! method. The slice! method is a method that changes the original array or string. Ruby 3.0.0 Reference Manual, slice! Example)

string = "hoge"
str = string.slice!(1)
puts str

#=>"o"

puts string
#=>"hge"
#"o"Is removed

With this method

def missing_char(string, num)
  string.slice!(num - 1)
  puts string
end

The original string has changed and is now output.

Recommended Posts

Delete any string
String
Java string
String replacement
Liar String