Ruby Beginning

前幾天開始看Ruby起因是網路上很多分享的project都是Rails,為了能夠加速了解理面的內容就來學一下Rails, 不過為了Rails必須要先打好Ruby的基礎。在這裡紀錄下學習過的語法避免自己忘光,光是昨天沒看語法我已經忘了不少XD。

Everything is object,在Ruby裡每一個東西都是物件,像直接對1這個object呼叫next兩次就會得到3

1
1.next.next

呼叫methods得到一個array包含所有的methods

1
1.methods

Ruby裡蠻特殊的是會回傳布林值的method傳參數是用’?’,其它的用’()’或空格

1
2
3
2.between?1,3  /* true */
"I am a Rubyist".index('R')
"I am a Rubyist".index 'R'

String operations

search

1
2
3
"[Luke:] I can’t believe it. [Yoda:] That is why you fail.".include?'Yoda'
"Ruby is a beautiful language".start_with?'Ruby'
"I can't work with any other language but Ruby".end_with?'Ruby'

在字串裡可以輕易地使用#{}把值傳進去,puts就是console output

1
2
3
a = 1
b = 1
puts "The number #{a} is less than #{b}"

case change

1
2
3
'This is Mixed CASE'.downcase
'This is Mixed CASE'.upcase
'This is Mixed CASE'.swapcase

split

1
'Fear is the path to the dark side'.split(' ')

concatenat

1
2
'Ruby'+'Monk'
'Ruby' << 'Monk'

replacing

1
2
3
"I should look into your problem when I get time".sub('I','We') /* only replace first found */
"I should look into your problem when I get time".gsub('I','We') /* replace all */
'RubyMonk'.gsub(/[aeiou]/,'1')  /* use RegEX, it must wrap it with / / */

Boolean operations

Like Java, use ==,&&,||,>=,<=

1
2
name = "Bob"
name == "Bob" /* true */

Conditional

if..else

1
2
3
4
5
6
7
8
9
def check_sign(number)
  if number > 0
    "#{number} is positive"
  elsif number < 25
    "#{number} is smaller than 25"
  else
    "#{number} is negative"
  end
end

Loop

remember to use ‘break’ to break loop

1
2
3
4
loop do
  monk.meditate
  break if monk.nirvana?
end

run N times

1
2
3
n.times do
  puts "Hello"
end

Arrays

access array

1
2
[1, 2, 3, 4, 5][2] /* answer is 3 */
[1, 2, 3, 4, 5][-1] /* answer is 5 */

add array, you could put different type object in Ruby Array

1
2
[1,2,3,4,5] << '6'
[1,2,3,4,5].push('6')

delete

1
2
[1,2,3,4,5].delete 3 /* [1,2,4,5] */
[1,2,3,4,5,6,7].delete_if{ |i| i < 4 }

filter elements of array

Ruby會有許多如底下的寫法, number代表存在於array裡面的object, 如果大於3會被挑出來

1
[1,2,3,4,5].select{ |number| number > 3}

array iteration

1
2
3
4
5
6
7
8
9
array = [1, 2, 3, 4, 5]
for i in array
  puts i
end

array = [1, 2, 3, 4, 5]
array.each do |i|
  puts i
end

Hashs

create a hash

1
2
3
4
5
restaurant_menu = {
  'Ramen' => 3,
  'Dal Makhani' => 4,
  'Tea' =>2
  }

fetch and modify value, like Array access

1
2
3
4
restaurant_menu['Ramen'] /* 3 */
restaurant_menu['Dal Makhani']=4.5

restaurant_menu.delete('Tea') /* delete it */

hash iteration

1
2
3
4
5
6
7
8
9
10
11
12
restaurant_menu = { 'Ramen' => 3, 'Dal Makhani' => 4, 'Coffee' => 2 }
restaurant_menu.each do |item, price|
  restaurant_menu[item] = price + (price * 0.1)
end

restaurant_menu.each_key do |item|
  puts item
end

restaurant_menu.each_value do |price|
  puts price
end

Class和def Function就留到下次再來寫。在Ruby Function中Method叫做Behaviour,Variable叫做State。

Comments