I have summarized the differences between slice and slice !. I would appreciate it if you could comment and point out any expressions that are easier to understand!
--slice and slice! - slice - slice!
--Practice --Problem --Answer (commentary)
--Summary --References
[Example] Extract the first element from the array and output the original array
point
--Methods that can retrieve specified elements from arrays and strings --Numeric when specifying elements --Starting from 0
slice
array = [0, 1, 2, 3, 4, 5]
num = array.slice(1)
puts num
puts array
#Terminal
#result of puts num
# 1
# =>Extract specified element
# puts array
# 0
# 1
# 2
# 3
# 4
# 5
slice!
--A method with an exclamation mark (!) Is called a destructive method. --Not only extract elements but also change their original shape --Delete the specified element
array = [0, 1, 2, 3, 4, 5]
num = array.slice!(1)
puts num
puts array
#Terminal
#result of puts num
# 1
# =>The elements that can be taken do not change
# puts array
# 0
# 2
# 3
# 4
# 5
# =>Extracted element (1) has been deleted
Let's solve the problem using slice
using fruits as an example.
Let's create a method that deletes the nth character from any character and outputs that character!
def str_check(string, num) #String(string)And what number do you want to delete(num)Have received
string.slice!(num - 1) #Because it starts from the 0th-You can delete the characters you want to retrieve by doing 1.
puts string # slice!You can output characters other than those deleted with
end
#Method call
str_check('apple', 1)
str_check('orange', 2)
str_check('grape', 4)
#Terminal output result
# pple
# oange
# grae
--Elements can be retrieved from strings and arrays by using the slice
method
--Specify a number when you want to retrieve an element
--Starting from 0th
--You can change the shape of the original string or array by using the slice!
method.
-Ruby 3.0.0 Reference Manual [slice]
-Ruby 3.0.0 Reference Manual [slice!]
Recommended Posts