code-quality

RUBY: when to prefer eql? over ==

RUBY: when to prefer eql? over ==

ruby
RUBY: when to prefer eql? over ==

I don’t remember since when did I pick up habit of preferring eql? over ==. But today I found out when should it be actually preferred and when it is ok to use ==.

Numbers

2.2.0 :001 > 1 == 1
 => true
2.2.0 :002 > 1 == 1.0
 => true
2.2.0 :003 > 1.eql?1
 => true
2.2.0 :004 > 1.eql?1.0
 => false

Code speaks itself! eql? is handy when we want to differentiate float and integer.

Hash

2.2.0 :008 > h1={a:1, b:2}
 => {:a=>1, :b=>2}
2.2.0 :009 > h2={a:1.0, b:2.0}
 => {:a=>1.0, :b=>2.0}
2.2.0 :010 > h1.eql?h2
 => false
2.2.0 :011 > h1==h2
 => true

eql? should be preferred in comparing hashes.

Strings

2.2.0 :006 > "foo"=="foo"
 => true
2.2.0 :007 > "foo".eql?"foo"
 => true

It doesn’t matter which one we use if we are comparing strings.

Reminder to self: Someday I will comeback and write in detail what is happening in each case.

Press Esc to return to the article
About the author

Prakash Poudel Sharma

Independent product manager & agentic engineering consultant

I'm an independent product manager, founder, and software builder based in Kathmandu. I help teams make product decisions and adopt agentic software development, drawing on over a decade of building software. I write about product thinking, engineering with AI, and hands-on experiments.

Keep reading

More on this

Join the conversation0 comments

What did you take away?

Thoughts, pushback, or a story of your own? Drop a reply below — I read every one.

Comments are powered by Disqus. By posting you agree to theirterms.

—
0:000:00