Reputation: 3
I am working on the following exercise in a course and I cannot wrap my head around this. I am very new to learning Rails, so please be patient with me. Currently the exercise wants me to write a method named tasty?
, which takes one argument:
def tasty?(ripe)
end
tasty?
should:
ripe
is true
ripe
is false
Specs are:
describe "tasty?" do
it "should return 'Yes' if ripe is true" do
expect( tasty?(true) ).to eq("Yes")
end
it "should return 'Not Yet' if ripe is false" do
expect( tasty?(false) ).to eq("Not Yet")
end
end
I wrote this:
def tasty?(ripe)
if "ripe == 'yes'"
( tasty?("true") ).==("yes")
end
if "ripe == 'not yet'"
( tasty?("false") ).==("not yet")
end
end
And receive this message when I run it:
exercise.rb:4: warning: string literal in condition
exercise.rb:7: warning: string literal in condition
Can anyone tell me what I am doing incorrectly? Thank you for your help.
Upvotes: 0
Views: 117
Reputation: 110685
As @eirikir has shown you the error or your ways, I will address another issue.
Try this:
def tasty?(ripe)
if ripe==true
puts "Yes"
else
puts "Not Yet"
end
end
Then
tasty?(true) #=> "Yes"
tasty?(false) #=> "Not Yet"
tasty?(nil) #=> "Not Yet"
tasty?(42) #=> "Not Yet"
The last returns "Not Yet" because:
42==true #=> false
Now try this:
def tasty?(ripe)
if ripe
puts "Yes"
else
puts "Not Yet"
end
end
Then:
tasty?(true) #=> "Yes"
tasty?(false) #=> "Not Yet"
tasty?(nil) #=> "Not Yet"
tasty?(42) #=> "Yes"
tasty?(42)
now returns "Yes"
because ripe
evaluates true
. That's because, in a logical expression (e.g., if..
) an object evaluates true
(is said to be "truthy") if it equals any value other than false
or nil
. It's said to be "falsy" if it equals false
or nil
.
@craig has shown how you can simplify the later expression.
Upvotes: 3
Reputation: 5598
Based on the spec, I would write it this way:
def tasty?(ripe)
ripe ? 'Yes' : 'Not Yet'
end
This can also be written more verbosely as:
def tasty?(ripe)
if ripe
'Yes'
else
'Not Yet'
end
end
The parameter to your method, ripe
is going to be - based on the spec you provided - true or false. So, in your method you need to check if ripe
is true or false and then return the correct string (i.e., Yes or Not yet).
My first example uses the ternary operator which is a shorthand expression for an if/else statement (as shown in my second code block).
Basically, it is just asking if ripe is true and, if so, it returns 'Yes'. If not, it returns 'Not Yet'.
Upvotes: 1
Reputation: 3842
The error you're receiving is due to a string in the if
statement; you should remove the quotes, e.g.:
if ripe == 'yes'
However, since ripe
is apparently always a boolean true
or false
and not a string "yes"
, you shouldn't be comparing it to "yes"
. You should be able to pass it directly to the if
statement:
if ripe
…
else
…
end
Then you can simply return the desired strings for the different conditions:
if ripe
"Yes"
else
"Not yet"
end
Does that make sense?
Upvotes: 3