1

I know I can use %w() as a shortcut to create an array. E.g. these should be equivalent:

FOO = %w(dog, cat)
BAR = ["dog", "cat"]

But when I use include to check what's included in these arrays:

FOO = %w(dog, cat)
BAR = ["dog", "cat"]

puts FOO.include? "dog" #false
puts BAR.include? "dog" #true

The first puts returns false while the second one returns true. Why is this happening?

Adam
  • 8,752
  • 12
  • 54
  • 96
  • 8
    Don't use commas with `%w`, otherwise it is including the string `dog,`. – Matt Dec 03 '20 at 19:16
  • 1
    @iBug, Adam may feel that your choice of name reflects your purpose in life. (Couldn't let it pass. :-) Perhaps the two comments can be deleted, after which you can shake hands (er, bump elbows) and this comment will vanish as well. – Cary Swoveland Dec 03 '20 at 20:16

2 Answers2

5

No these arrays are not equivalent

FOO = %w(dog, cat)
BAR = ["dog", "cat"]

But these are

FOO = %w(dog cat)       # note that the `%w` syntax doesn't need commas.
BAR = ["dog", "cat"]

That said, your first version does not FOO.include? "dog" because it includes "dog," and "cat".

Adam
  • 8,752
  • 12
  • 54
  • 96
spickermann
  • 100,941
  • 9
  • 101
  • 131
2

In addition to @spickermann's answer, printing the array themselves is often more than enough to identify the issue.

Ruby has a built-in method p that prints out any object in a "representative" format, similar to Python's repr().

FOO = %w(dog, cat)
p FOO  # => ["dog,", "cat"]
#                ^ hey, bro?
iBug
  • 35,554
  • 7
  • 89
  • 134