1

I'm very new to Ruby so please go easy on me. I have this small function that doesn't want to perform an intersection command. If I go into irb and enter the arrays then set the intersection command like: third_array = array1 & array2, third_array returns the common element. But when I run this snippet through irb, it just returns [ ]. Any suggestions?

class String

  define_method(:antigrams) do |word2|

    array1 = []
    array2 = []
    array1.push(self.split(""))
    array2.push(word2.split(""))
    third_array = array1 & array2
      third_array
  end

end
4
  • There's no need to use define_method here when def would do the job. define_method is reserved for cases where you don't know the name of the method in advance, it's computed, or the block inside is generated dynamically somehow. Commented Apr 24, 2017 at 4:24
  • G McMahon, are you by any change taking a course where define_method is introduced before def (i.e., def antigrams(word2))? I ask because, as @tadman mentions, using define_method here is a bit odd, but I could see where an instructor might believe it's useful to cover define_method before def. Commented Apr 24, 2017 at 6:35
  • Yes Cary, that is the case. I've seen 'def' used but haven't really used it myself. Maybe in my second week!? Commented Apr 24, 2017 at 14:43
  • define_method is intended for meta-programming, that is code that writes code, so dropping that people on week one is really throwing them into the deep end. Every introduction I've ever seen or written always starts with def. Commented Apr 24, 2017 at 17:05

1 Answer 1

4

After looking at what you have, I think your code boils down to this:

class String
  def antigrams(word)
    self.chars & word.chars
  end
end

"flurry".antigrams("flagrant")
# => ["f", "l", "r"]

If you're calling split('') on a word that's effectively the same as chars, though a lot less efficient. Another mistake was pushing a whole array into an array, which creates a nested array of the form [ [ 'f', 'l', ... ] ]. Since the two resulting array-of-arrays have nothing in common, their inner arrays are different, the & operation returns an empty array.

What you meant was to concatenate the one array to the other, something that can be done with += for example.

Whenever you're curious what's happening, either use irb to try out chunks of code, or p to debug at different points in your method.

Sign up to request clarification or add additional context in comments.

1 Comment

That is great! Thank you! +1 but it's not publicly recorded...too new :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.