Ruby Study

最近都在看CSS沒什麼時間繼續看Ruby,今天上codecademy練習ruby。 在這裡紀錄一下之前沒看過的語法。

Multiple comments

1
2
3
4
=begin
this is comment,
i am comment too.
=end

Get input from console

1
2
print "Integer please: "
user_num = Integer(gets.chomp)

Different between string.downcase and string.downcase!

With ! the user’s string is modified in-place; otherwise, Ruby will create a copy of user_input and modify that instead

1
2
3
4
5
name = "Samuel"
downcase_name = name.downcase
puts name  # "Samuel"
downcase_name = name.downcase!
puts name  # "samuel"

Hash sort_by and Array sort!

1
2
3
4
5
6
7
8
h = Hash.new(0)
h.sort_by { |a,b| b }  # we can sort by value

my_array = [3, 4, 8, 7, 1, 6, 5, 9, 2]
my_array.sort! # [1, 2, 3, 4, 5, 6, 7, 8, 9]

#descending order
my_array.sort! { |a,b| b <=> a} # [9, 8, 7, 6, 5, 4, 3, 2, 1]

What’s Symbol? it’s not a string

1
2
3
4
5
6
7
8
"string" == :string # false

"string".object_id == "string".object_id  # false

:symbol.object_id == :symbol.object_id # true

"string".to_sym == :string # true
"string".intern == :string # true, inter is the same as to_sym

Why need symbol? 主要是用來當hash的key以及用來參考到method的名字

  1. They’re immutable, meaning they can’t be changed once they’re created
  2. Only one copy,節省記憶體
  3. Hashes that use symbols instead of strings as keys work faster

來看一下怎麼使用

1
2
3
4
5
6
7
8
9
10
movies = {
  :name => "star_war",
  :age => "1970"
}

#But since ruby 1.9 hash become more compact
movies = {
  name: "star_war",
  age: "1970"
}

switch conidition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
case language
when "JS"
  puts "Websites!"
when "Python"
  puts "Science!"
when "Ruby"
  puts "Web apps!"
else
  puts "I don't know!"
end

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

Ternary conditional expression

1
puts 3 < 4 ? "hello world"  : "evil"  # hello world

Conditional assignment.

1
2
3
4
5
favorite_book = nil
puts favorite_book  # won't output anything

favorite_book ||= "Cat's Cradle"
puts favorite_book  # Cat's Cradle

upto and downto

1
2
3
4
95.upto(100) { |num| print num } # 95 96 97 98 99 100

# also apply to alphabet
"L".upto("P") { |word| print word }

Call and Response

Here we use symbol to reference a method name. For example, we want to check variable has next method or not.

1
2
age = 30
age.respond_to?(:next) # true

Comments