Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Armaan Dhanji
Armaan Dhanji
4,664 Points

Confusion regarding unusual result from equal? in Ruby for object comparison

I'm totally confused about why the answer i'm getting for this equality check is false, when I thought the two variable objects I created are in the same memory location? (Doesn't ruby have an optimization where if the string values are the same, a new object is not created but rather, a pointer to the first one is made?).

x = "hello" y = "hello"

x.equal?(y) -> false Shouldn't it return true? I know that if I do an object_id check, they will have different id's, but doesn't different id's mean different memory addresses. TLDR; when I made two variables with the same values for strings, and I do the equal? check, shouldn't it return true? (because equal? checks for if they are the same object, and I thought ruby does not create a new object for strings if the value of the string is one which has already been created previously).

1 Answer

John O.
John O.
4,680 Points

When you make 2 separate variable declarations:

x = "hello"
y = "hello"

Ruby stores the same string in 2 distinct memory locations

If you want to reference the same exact string (in memory) with 2 variables:

a = b = "my_string"

then

a.equal?(b)

will return true