Home > Enterprise >  Issues with basic ruby if statement
Issues with basic ruby if statement

Time:10-18

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.

CodePudding user response:

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

CodePudding user response:

You can also use puts "Name wasn't on the list" unless friends.include? (name), here in a simple method:

def name_on_list(friends, name)
  puts "Name wasn't on the list" unless friends.include?(name)
end

friends = ["Kevin", "Karen", "Oscar"]
name_on_list(friends, "Fred")

You can remove the "Array" from the array declaration.

The function takes the friends and the name as arguments.

Within the function, I use the one-liner to print the text when the name is not included. I tend to use parenthesis to pass parameters but they are optional.

  • Related