ruby的安装与使用

安装rbenv

rbenv 用来管理多个版本的 ruby 在用户目录的安装和使用。

1
2
3
git clone git://github.com/sstephenson/rbenv.git ~/.rbenv
git clone git://github.com/AndorChen/rbenv-china-mirror.git ~/.rbenv/plugins/rbenv-china-mirror
vim ~/.zshrc

添加

1
2
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

1
2
➜  ~ rbenv -v
rbenv 1.1.1

使用rbenv安装ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
➜  ~ rbenv versions # 显示本地系统可用ruby版本(*号为当前shell使用的ruby版本)
system
2.2.1
* 2.2.2 (set by /Users/suse/.rbenv/version)
➜ ~ rbenv version # 显示当前shell使用的ruby版本
2.2.2 (set by /Users/suse/.rbenv/version)
➜ ~ rbenv global system # 设置全局ruby版本为system
➜ ~ rbenv versions
* system (set by /Users/suse/.rbenv/version)
2.2.1
2.2.2
➜ ~ rbenv version
system (set by /Users/suse/.rbenv/version)
➜ ~ rbenv install -l|--list # 显示远程ruby的可安装版本
➜ ~ rbenv install 2.4.2 # 安装2.4.2版本ruby
➜ ~ rbenv versions
* system (set by /Users/suse/.rbenv/version)
2.2.1
2.2.2
2.4.2
➜ ~ rbenv global 2.4.2
➜ ~ ruby -v
ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin16]

使用实例

1
➜  ruby vim ruby1.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/ruby

# this one is like your scripts with argv
def puts_two(*args)
arg1, arg2 = args
puts "arg1: #{arg1}, arg2: #{arg2}"
end
# ok, that *args is actually pointless, we can just do this
def puts_two_again(arg1, arg2)
puts "arg1: #{arg1}, arg2: #{arg2}"
end
# this just takes one argument
def puts_one(arg1)
puts "arg1: #{arg1}"
end
# this one takes no arguments
def puts_none()
puts "I got nothin'."
end
puts_two("Da","Wang")
puts_two_again("Da","Wang")
puts_one("First!")
puts_none()
1
2
3
4
➜  ruby ruby ruby1.rb
arg1: Da, arg2: Wang
arg1: Da, arg2: Wang
arg1: First!

gem

gem 是 Ruby 模块 (叫做 Gems) 的包管理器。其包含包信息,以及用于安装的文件。
gem通常是依照”.gemspec”文件构建的,包含了有关Gem信息的YAML文件。Ruby代码也可以直接建立Gem,这种情况下通常利用Rake来进行。

配置gem源

1
2
3
4
5
6
7
8
9
10
➜  ~ gem sources -l
*** CURRENT SOURCES ***

https://rubygems.org/
➜ ~ gem sources --remove https://rubygems.org/
➜ ~ gem sources -a https://gems.ruby-china.org
➜ ~ gem sources -l
*** CURRENT SOURCES ***

https://gems.ruby-china.org

使用gem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
➜  ~ gem list --local # 列出本地已安装的gem包

*** LOCAL GEMS ***

bigdecimal (default: 1.3.0)
did_you_mean (1.1.0)
io-console (default: 0.4.6)
json (default: 2.0.4)
minitest (5.10.1)
net-telnet (0.1.1)
openssl (default: 2.0.5)
power_assert (0.4.1)
psych (default: 2.2.2)
rake (12.0.0)
rdoc (default: 5.0.0)
test-unit (3.2.3)
xmlrpc (0.2.1)
➜ ~ gem list --remote # 列出远程gem包
➜ ~ gem install sass # 安装sass
➜ ~ gem uninstall sass # 卸载sass
➜ ~ gem search compass # 安装sass
➜ ~ cd Workspace/ruby
➜ ruby ls
➜ ruby gem fetch compass
Fetching: compass-1.0.3.gem (100%)
Downloaded compass-1.0.3
➜ ruby ls
compass-1.0.3.gem

常用网站

官网: http://www.ruby-lang.org/en/
ruby-china: https://ruby-china.org/
gem: https://rubygems.org/
ruby-china gems镜像: https://gems.ruby-china.org/
ralis: http://rubyonrails.org/