Skip to content

Instantly share code, notes, and snippets.

@randalmaile
Last active December 30, 2015 16:09
Show Gist options
  • Save randalmaile/7852685 to your computer and use it in GitHub Desktop.
Save randalmaile/7852685 to your computer and use it in GitHub Desktop.
If Statements checkpoint
-In Ruby, the last evaluated line of a method is returned from the method by default.
-Also note that we must always use end to close an if statement.
- Note that elsif is not what you might think (from JS) "else if" - remember the syntax!
-One Line Conditionals
-You can also use if and unless at the end of one line statements:
```
gets_discount = true
price *= 0.8 if gets_discount
skip_tax = true
price += price * 0.1 unless skip_tax
```
-If gets_discount is true (which it is) then you'll discount the price by 20%. Unless skip_tax is true, you'll add a 10% tag to the price.
MICHAL - thx for the tip - I finally got it - I was thinking that I had to run the RSpect test inside the interpreter. Guess not. Thx!
``` Bloc output - if statements
```
```
favorite_number should return 'Too low' if the guess is low
favorite_number should return 'Too high' if the guess is high
favorite_number should return 'You got it!' if the guess is right
```
``` Bloc output - and/or
```
lock should return unlocked for 3258
lock should return locked for 1111
lock should return unlocked for other valid combinations
can_i_get? returns true if user wants a computer and has $1,000
can_i_get? returns false for a comptuer if they don't have $1,000
can_i_get? returns true for a iPad if they have $500
can_i_get? returns false for a iPad if they have less than $500
#IF STATEMENTS
def favorite_number(fav, guess)
if guess < fav
"Too low"
elsif guess > fav
"Too high"
else
"You got it!"
end
end
describe "favorite_number" do
it "should return 'Too low' if the guess is low" do
favorite_number(10, 1).should eq("Too low")
end
it "should return 'Too high' if the guess is high" do
favorite_number(5, 11).should eq("Too high")
end
it "should return 'You got it!' if the guess is right" do
favorite_number(11, 11).should eq("You got it!")
end
end
# AND / OR
def lock(a,b,c,d)
if (a==3 || a ==5 || a==7) && (b==2) & (c==5 || c==6) && (d==8 || d==9 || d==0)
"unlocked"
else
"locked"
end
end
def can_i_get?(item, money)
if (item == "computer" && money >= 1_000)
true
elsif (item == "computer" && money < 1_000)
false
elsif (item == "ipad" && money >= 500)
true
else
false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment