openlang

ruby delete behaving unexpectedly?

Changing an integer array gives me a surprising result under ruby 2.6.1p33 (2019-01-30 revision 66950) [x86_64-darwin13] :

values = [
  2, 134, 163, 215, 108
]
=> [2, 134, 163, 215, 108]
target = 108
=> 108
values.delete(target)
=> 108

small changes to how i write it keep producing that result.

am i writing this incorrectly, is another command overriding what this does or, even worse, could something be corrupted? how can i check, becuase i'm unsure?

The conversation continues 2

Follow the reasoning
  1. Permalink

    According to the Array#delete (https://ruby-doc.org/core-3.0.0/Array.html#method-i-delete) documentation:

    Without a supplied block, deletes every element ele from self where ele == obj; the final removed element is returned...

    Here target holds 108, which explains the displayed value when you assign it. Next, values.delete(target) finds a matching element within values, removes that element, and gives back the value held in target.

  2. Permalink

    Which result did you think you would see when you ran this code? The example you've posted here appears to behave just as it should.

    Look at the contents of values right after running the example you posted - the last element should no longer be there.

    Ruby's delete() may have a somewhat unexpected definition. You could reasonably imagine getting a changed copy back while keeping the initial array intact, allowing a chain such as:

    values.delete(target).delete(163)

    with a separate bang form available to change the array itself:

    values.delete!(target)

    however, that isn't how this method works. Calling ordinary delete() changes the receiver array directly.

Other sides of the same question

  1. Choosing enum entries randomly with GDScript in Godot 3.3 without listing each one?

    Here's the enum declaration I'm using in GDScript: I'd like to choose an enum variant randomly without listing every possible…

    Replies 2Latest activity gdscript
  2. Nim remainder syntax

    How is modulus expressed in Nim? cell % 7 == 0 gives undeclared identifier: '%' Neither a Google search nor looking through S…

    Replies 2Latest activity nim
  3. Returning results from an APL function

    How do I make my function return something once execution has finished? For instance, I have: ROUTINE N ? N ⍴ 12 //That gener…

    Replies 2Latest activity apl