rbenv and rvm

rbenv

We're going to use rbenv to install and manage our Ruby versions.

To do this, run the following commands in your Terminal:

brew install rbenv ruby-build

# Add rbenv to bash so that it loads every time you open a terminal

echo 'if which rbenv > /dev/null; then eval "$(r......

OOP in Ruby

scope

An important aspect of Ruby classes is scope. The scope of a variable is the context in which it's visible to the program.

When dealing with classes, you can have variables that are

available everywhere (global variables), like $manufacturer

only available certain methods (lo......

Blocks, Procs and Lambdas

Blocks.collect (和.map等价)

The collect method takes a block and applies the expression in the block to every element in an array.

my_nums = [1, 2, 3]

my_nums.collect { |num| num ** 2 }

# ==> [1, 4, 9]

# my_nums hasn't changed:

my_nums

# ==> [1, 2, 3]

my_nums.collect! { |num| num ** ......

Ruby的Array和Hash

Arraydemo_array = [100, 200, 300, 400, 500]

print demo_array[2] # ==> return 300

# 2维数组

demo_2d_array = [[1,2,3],[4,5,6],[7,8,9]]

# 遍历数组

friends = ["Milhouse", "Ralph", "Nelson", "Otto"]

friends.each { |x| puts "#{x}" }

# Instead of typing o......

Symbol in Ruby

What are Symbols?

Symbols always start with a colon (:). They must be valid Ruby variable names.

You can think of a Ruby symbol as a sort of name.

It's important to remember that symbols aren't strings:

"string" == :string # false

Above and beyond the different synt......

Short-circuit Evaluation

def a

puts "A was evaluated!"

return true

end

def b

puts "B was also evaluated!"

return true

end

puts a || b

puts "------"

puts a && b

return

A was evaluated!

true

------

A was evaluated!

B was also evaluated!

true

nil

Conditional Assignment

We've seen that we can use the = operator to assign a value to a variable. 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 = assign......

Combined Comparison Operator

The combined comparison operator looks like this: <=>.

It returns 0 if the first operand (item to be compared) equals the second, 1 if first operand is greater than the second, and -1 if the first operand is less than the second.

book_1 = "A Wrinkle in Time"

book_2 = "A Brie......

Ruby的方法和代码块

def prime(n)

puts "That's not an integer." unless n.is_a? Integer

is_prime = true

for i in 2..n-1

if n % i == 0

is_prime = false

end

end

if is_prime

puts "#{n} is prime!"

else

puts "#{n} is not prime."

end

end

prime(2)

prime(9)

prime(11)

prime(51)

prime(97)

# Spl......

Ruby的控制流

1.if/else/unlessprint "Integer please: "

user_num = Integer(gets.chomp)

if user_num < 0

puts "You picked a negative integer!"

elsif user_num > 0

puts "You picked a positive integer!"

else

puts "You picked zero!"

end

hungry = false

unless hungry # unle......