Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issues with basic ruby if statement

I’m trying to set up this code to check if a specific name exists within the array. In this instance, I want to see if Fred is on the list and if it isn’t, put "Name wasn’t on the list" underneath.

friends = Array["Kevin", "Karen", "Oscar"]

if (puts friends.include? "Fred" == false)
  puts ("Name wasn't on the list")
end

I’m new to ruby so I’m unsure if this is the correct method. Any help would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

friends = Array["Kevin", "Karen", "Oscar"]

This is not wrong, just overdone. friends = ["Kevin", "Karen", "Oscar"] is fine.

if (puts friends.include? "Fred" == false)
  puts ("Name wasnt on the list")
end

The if (puts friends.include? "Fred" == false) line looks innocent, but contains a surprising amount of mistakes, the most important being that puts always returns nil. This version works :

unless friends.include? "Fred" 
  puts "Name wasnt on the list"
end
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading