dennismonsewicz
dennismonsewicz

Reputation: 25542

Ruby: Trying to better understand the use of Hash#delete

I have seen a lot of examples of Ruby classes that utilize the Hash method of delete and I am not sure what the advantage of using it would be.

Example:

class Example
  def initialize(default_params = {})
    @foo = default_params.delete(:bar)
  end
end

Any insight would be extremely helpful! Thanks!

Upvotes: 0

Views: 52

Answers (1)

jamesfzhang
jamesfzhang

Reputation: 4473

Hash#delete is useful in the following situation:

def method(options)
  if options.delete(:condition)
    # Do something if options[:condition] is true
  else
    # Otherwise do something else
  end

  # Now options doesn't have the :conditions key-value pair.
  another_method_that_doesnt_use_the_condition(options)
end

I'm unsure if the specific example you pulled should be using Hash#delete.

Upvotes: 1

Related Questions