I want to delete elements in the array by specifying a range, but I can't.

Asked 2 years ago, Updated 2 years ago, 29 views

In Ruby's array, I would like to range and delete the elements of the array.
The following URL does not produce exactly the same result.
https://uxmilk.jp/24060

Ruby version is ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin16].

 target=[1,2,3,4,5,6,7]
aaa=target.slice!(1,3)
paaaaaa (literally, "paaaaa


a = ["a", "b", "c", "d", "e" ]
pa.slice! (1,3)

The above results are as follows.

[2,3,4]#=> Does Not Become [1,5,6,7]
Does not get ["b", "c", "d"]#=>["a", "e"]

I don't know the cause because I didn't do what I expected.
What should I do to get the desired behavior?
I look forward to your kind cooperation.

ruby

2022-09-29 21:56

2 Answers

If you call like slices(1,3), the index of the first argument returns a partial string of characters in the second argument.
In other words, 1,3 takes 3 characters from the 2nd (1+1)th character because it is the beginning of 0.
https://docs.ruby-lang.org/ja/latest/class/Array.html#I_SLICE

When you make a call like slices!(1,3), you remove the second argument character string from the receiver from the index of the first argument.
Then, unlike slices, the return value returns the deleted element instead of the receiver (deleted array.
https://docs.ruby-lang.org/ja/latest/class/Array.html#I_SLICE--21

In other words, the purpose of your code has been achieved with a.slices!(1,3) and without worrying about the return value
If you access a again, ['a', 'e'] has been created.


2022-09-29 21:56

Ruby's standard library method is

  • Returns a copy of a receiver object with some action
  • What modifies the receiver object itself

Yes, the former is called the "non-destructive" method, and the latter is called the "destructive" method.If there are non-destructive and destructive methods that do the same, it is customary to name the method more destructive.

(Note that if there is a method with the same function and it is a custom, it is not generally a destructive method if it is marked with "!")

slices/slices! is also this pattern, where the former returns the result of slicing the array (the original object remains), and the latter changes the called object itself.

Note that the return value of the destructive method depends on the method. slice! returns the deleted element, but some return self if not niL.

For example,

str2=str.sub(/hoge/, 'fuga') 
# After that, I will operate str2 and not touch str.

If you accidentally use sub! with these codes, they both behave the same way if they are converted, but if they are not converted, str2 will actually have a copy of str, but nil.If the conversion occurs only rarely, this is a rather confusing bug.

Therefore, be very careful when using non-destructive and destructive methods.


2022-09-29 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.