Chef (1) Install Chef Development Kit and Basic Ruby Syntax
1. Install Chef Development Kit:
Down load the deb for Ubuntu from https://downloads.chef.io/chefdk.
$ sudo dpkg -i <deb filename> $ echo 'eval "$(chef shell-init bash)"' >> ~/.bashrc $ source ~/.bashrc
Check the installation:
$ ls /opt/chefdk/bin $ which ruby # ruby is installed with chef
2. Ruby Syntax:
Open the Ruby REPL in the terminal:
$ irb
Ruby is similar to Python. We don't need to declare the variable type. Let's define a variable.
> variable = 3 > variable
if statement in Ruby.
num = 2 if num%2 == 0 puts "even" else puts "odd" end
3. Ruby String and Heredoc:
The #{} operator performs expression substitution inside a string literal.
apple_num = 10
bob_say = "I have #{apple_num} apples."
Heredoc is convenient to represent a long string. The Heredoc expression starts with << operator.
apple_num = 10
<<APPLE
I like to eat apple.
I have #{apple_num} apples.
APPLE
4. Ruby Array:
arr = ["alice", "bob", "cat", "dog", "echo", "frog"] puts arr.first puts arr.last puts arr[2] puts arr[1..3] # ["bob", "cat", "dog"]
The .. operator creates a range from start point to end point inclusive.
5. Ruby Hash:
Hash in Ruby is similar to the dictionary in Python.
person = {name: "bob", age: 30}
person[:name]
# "bob"
person[:age]
# 30
If you want to use the string literal as the key, you can use Hash Rocket (=>) operator to define Hash.
person = {"name"=> "bob", "age"=> 30}
person["name"]
# "bob"
person["age"]
# 30
6. Methods, Classes, and Modules
class Bacon
def cook(temperature)
#...
end
end
module Edible
# ...
end
留言
張貼留言