HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Custom delete method refactoring

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
refactoringcustomdeletemethod

Problem

I'm new to Ruby and don't know all the methods, so I was thinking there would probably be and easier way to do something like this. I'd love any input on how to refactor this.

define_singleton_method(:delete) do |id|
        revised_words = []
        @@words.each do |word|
          if word.id() != id
            revised_words.push(word)
          else
            Definition.delete_by_word_id(id)
          end
        end
        @@words = revised_words
      end

Solution

Some notes:

-
An array is not the best data structure to store the words, operations will be O(n). Better a hash {word_id => word}

-
Use 2-space indentation.

Then you can write:

define_singleton_method(:delete) do |id|
  if @@words.delete(id)        
    Definition.delete_by_word_id(id)
  end
end

Code Snippets

define_singleton_method(:delete) do |id|
  if @@words.delete(id)        
    Definition.delete_by_word_id(id)
  end
end

Context

StackExchange Code Review Q#100986, answer score: 2

Revisions (0)

No revisions yet.