Ruby笔记

字数 1115 · 2019-04-04

https://learnxinyminutes.com/docs/ruby/
Pry - IRB alternative

Hello World

1
p 'Hello World!'

变量

局部变量
以小写字母或 _ 开头
实例变量
@ 开头
类变量
@@ 开头
全局变量
$ 开头

伪变量

self
true
false
nil - null/undefined
__FILE__ - 当前源文件的名字
__LINE__ - 当前行数

算符

数学算符
+ - * / % **
比较算符
== != > < >= <=
<=> - a<=>b a=b 返回0,a>b 返回1,a<b 返回-1
===
.eql? 值和类型都相同时返回true
.euqal? 两边为同一个对象返回true
赋值算符
= += -= *= /= %= **=
位运算符
& | ~ ^ >> <<
逻辑算符
and or not && || !
三目算符
?:
Range算符
.. - (1..5) 1, 2, 3, 4, 5
... - (1...5) 1, 2, 3, 4
defined?

1
2
3
4
5
6
7
defined? variable # True if variable is initialized
defined? foo    # => "local-variable"
defined? $_     # => "global-variable"
defined? bar    # => nil (undefined)
defined? method_call # True if a method is defined
defined? puts        # => "method"
...

Dot “.” and Double Colon “::”

注释

1
2
3
4
# 注释
=begin
多行注释
=end

控制语句

if

1
2
3
4
5
6
7
if conditional [then]
   code...
[elsif conditional [then]
   code...]...
[else
   code...]
end

case

1
2
3
4
5
6
case expression
[when expression [, expression ...] [then]
   code ]...
[else
   code ]
end

while

1
2
3
4
while conditional [do]
   code
   [return ...] 
end

方法

返回值为最后一个语句的值
调用方法可以不加括号

1
2
3
def method_name [( [arg [= default]]...[, * arg [, &expr ]])]
   expr..
end

模块

打包类,方法,常量

数据结构

Array

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

Hash

1
2
3
4
5
colors = {'red'=> 0xf00, 'green'=> 0x0f0, 'blue'=> 0x00f}
colors['red']
colors.each do |k, v|
    print k, " is ", v, "\n"
end

Range

1
2
3
(10..15).each do |n| 
   print n, ' ' 
end

OOP

Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Customer
   @@no_of_customers = 0
   def initialize(id, name, addr)
        @cust_id = id
        @cust_name = name
        @cust_addr = addr
   end
   def hello
        puts "Hello Ruby!"
   end
   # accessor methods
   def getName
        @cust_name
   end
   # setter methods
   def setName=(value)
      @cust_name = value
   end
end

cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust1.hello
1
2
3
4
5
6
7
class Human
   def initialize(name)
      @name = name
   end
   # same as getter/setter
   attr_accessor :name
end

To make the variables available from outside the class, they must be defined within accessor methods
Similar to accessor methods, which are used to access the value of the variables, Ruby provides a way to set the values of those variables from outside of the class using setter methods

文件

1
2
3
4
open('test.txt', 'w') do |file|
   file.puts('line one.')
   file.puts('line two.')
end

Rake

Ruby Make

带参数的任务:

1
2
3
task :new, [:name] do |task, args|
  ruby "_scripts/new_post.rb #{args.name}"
end
1
rake new[post1]