Tuesday, April 12, 2016

Ruby_Lesson_The Zen of Ruby

You're in Control
1.Ruby is a Delight
As a language, Ruby prioritizes programmer productivity over program optimization. This means that Ruby may not always run a program in the fastest way possible, but it strives to be a language that programmers (like you!) find easy and fun to use. The more intuitive a language's syntax is, the more productive its users can be. You're in control, not the machine!
2.A Simpler 'If'
If the "do something" is a short, simple expression, however, we can move it up into a single line. The syntax looks like this:
expression if boolean
Ruby will expect an expression followed by if followed by a boolean. The order is important. You can do this:
puts "It's true!" if true
but not this:
if true puts "It's true!"
It's also important to note that you don't need an end when you write your if statement all on one line.
3.The One-Line Unless
You can do the exact same thing with the unless statement. The order is the same as before: something for Ruby to do, the unless keyword, and then an expression that evaluates to true or false.
Remember, you don't need an end when you write a one-line if or unless!
puts "one line" unless false
4.One Good Turn Deserves a Ternary
An even more concise version of if/else is the ternary conditional expression. It's called "ternary" because it takes three arguments: a boolean, an expression to evaluate if the boolean is true, and an expression to evaluate if the boolean is false.
The syntax looks like this:
boolean ? Do this if true: Do this if false
An example might be
puts 3 < 4 ? "3 is less than 4!" : "3 is not less than 4."
Remember: the order of arguments is important, and you don't need an end for this version of if/else.
puts 3==4 ? "true" : "false"
5.When and Then: The Case Statement
The syntax looks like this:
case language
when "JS"
  puts "Websites!"
when "Python"
  puts "Science!"
when "Ruby"
  puts "Web apps!"
else
  puts "I don't know!"
end
But you can fold it up like so:
case language
  when "JS" then puts "Websites!"
  when "Python" then puts "Science!"
  when "Ruby" then puts "Web apps!"
  else puts "I don't know!"
end
Tips & Tricks
6.Conditional Assignment
But what if we only want to assign a variable if it hasn't already been assigned? For this, we can use the conditional assignment operator: ||=. It's made up of the or (||) logical operator and the normal = assignment operator.
favorite_book = nil
puts favorite_book
favorite_book ||= "Cat's Cradle"
puts favorite_book
favorite_book ||= "Why's (Poignant) Guide to Ruby"
puts favorite_book
favorite_book = "Why's (Poignant) Guide to Ruby"
puts favorite_book

  1. favorite_book is set to nil, which is Ruby for "nothing." When you try to puts it to the screen, you get exactly that: nothing!
  2. Now our variable is conditionally set to "Cat's Cradle." Since the value of the variable was nothing before, Ruby goes ahead and sets it, so you see "Cat's Cradle" printed out.
  3. We try conditional assignment again, this time with "Why's (Poignant) Guide to Ruby." But wait! Our variable already has a value, "Cat's Cradle," so it stays set to that value and that's what we see printed out.
  4. Finally, we use regular old assignment to tell Ruby to reset favorite_book to "Why's (Poignant) Guide to Ruby," which it gladly does.
8.Implicit Return
For instance, if you don't tell a JavaScript function exactly what to return, it'll return undefined. For Python, the default return value is None. But for Ruby, it's something different: Ruby's methods will return the result of the last evaluated expression.
This means that if you have a Ruby method like this one:
def add(a,b)
  return a + b
end
You can simply write:

def add(a,b)
  a + b
end
And either way, when you call add(1,1), you'll get 2.
9.Short-Circuit Evaluation
Ruby does this via short-circuit evaluation. That means that Ruby doesn't look at both expressions unless it has to; if it sees
false && true
it stops reading as soon as it sees && because it knows false && anything must be false.
Knowing What to Use
10.The Right Tool for the Job
If we want to do something a specific number of times, we can use the .times method, like so:
5.times { puts "Odelay!" }
If we want to repeat an action for every element in a collection, we can use .each:
my_array.each{ |x| puts x if x%2==0}
11.Up the Down Staircase
If we know the range of numbers we'd like to include, we can use .upto and .downto.
We might use .upto to print out a specific range of values:
95.upto(100) { |num| print num, " " }
# Prints 95 96 97 98 99 100
and we can use .downto to do the same thing with descending values.
"L".upto("P") {|letter| puts letter}
12.Call and Response
.respond_to? takes a symbol and returns true if an object can receive that method and false otherwise. For example,
[1, 2, 3].respond_to?(:push)
would return true, since you can call .push on an array object. However,
[1, 2, 3].respond_to?(:to_sym)
would return false, since you can't turn an array into a symbol.
age = 26
age.respond_to?(:next)

.next will return the integer immediately following the integer it's called on, meaning 4.next will return 5
13.Being Pushy
Instead of typing out the .push method name, you can simply use <<, the concatenation operator (also known as "the shovel") to add an element to the end of an array:
[1, 2, 3] << 4
# ==> [1, 2, 3, 4]
Good news: it also works on strings! You can do:
"Yukihiro " << "Matsumoto"
# ==> "Yukihiro Matsumoto"
Use the concatenation operator instead of .push and +.
alphabet = ["a", "b", "c"]
alphabet.push("d") #
caption = "A giraffe surrounded by "
caption += "weezards!"

caption = "A giraffe surrounded by "
caption << "weezards!"

14.String Interpolation
You can always use plain old + or << to add a variable value into a string:
drink = "espresso"
"I love " + drink
# ==> I love espresso
"I love " << drink
# ==> I love espresso
But if you want to do it for non-string values, you have to use .to_s to make it a string:
age = 26
"I am " + age.to_s + " years old."
# ==> "I am 26 years old."
"I am " << age.to_s << " years old."
# ==> "I am 26 years old."
This is complicated, and complicated is not the Ruby way. A better way to do this is with string interpolation. The syntax looks like this:
"I love #{drink}."
# ==> I love espresso.
"I am #{age} years old."
# ==> I am 26 years old.
All you need to do is place the variable name inside #{} within a string!










No comments :

Post a Comment