Everything is object,在Ruby裡每一個東西都是物件,像直接對1這個object呼叫next兩次就會得到3
1
1.next.next
呼叫methods得到一個array包含所有的methods
1
1.methods
Ruby裡蠻特殊的是會回傳布林值的method傳參數是用’?’,其它的用’()’或空格
123
2.between?1,3/*true*/"I am a Rubyist".index('R')"I am a Rubyist".index'R'
String operations
search
123
"[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
123
a=1b=1puts"The number #{a} is less than #{b}"
case change
123
'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
12
'Ruby'+'Monk''Ruby'<<'Monk'
replacing
123
"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 ==,&&,||,>=,<=
12
name="Bob"name=="Bob"/* true */
Conditional
if..else
123456789
defcheck_sign(number)ifnumber>0"#{number} is positive"elsifnumber<25"#{number} is smaller than 25"else"#{number} is negative"endend
Loop
remember to use ‘break’ to break loop
1234
loopdomonk.meditatebreakifmonk.nirvana?end
run N times
123
n.timesdoputs"Hello"end
Arrays
access array
12
[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