首页 > 代码库 > 【Ruby编程】Ruby安装配置和学习总记

【Ruby编程】Ruby安装配置和学习总记

【转载请注明出处:http://blog.csdn.net/leytton/article/details/37411721

1、运行环境 

win7    ruby 1.9.3p545

2、学习资源

苏勇老师Ruby开发语言视频教程  http://edu.51cto.com/course/course_id-1414.html

在浏览器上试用 Ruby   http://tryruby.org/levels/1/challenges/0  (PS:注意输入法要切换到英文)

20分钟体验 Ruby         https://www.ruby-lang.org/zh_cn/documentation/quickstart/

文档 - Ruby 官方网站   https://www.ruby-lang.org/zh_cn/documentation/

rubymonk教程           http://rubymonk.com/

Ruby系列博文              http://blog.csdn.net/aotian16/article/category/1073898

3、安装和配置

下载 Ruby - Ruby 官方网站    https://www.ruby-lang.org/zh_cn/downloads/  

我用win7开发的,所以下载了rubyinstaller  http://rubyinstaller.org/   

根据提示"If you don’t know what version to install and you’re getting started with Ruby, we recommend you use Ruby 1.9.3 installers. These provide a stable language and a extensive list of packages (gems) that are compatible and updated."

我选择下载Ruby 1.9.3-p545

安装rubyinstaller时注意勾选“Add Ruby executable to your PATH” 把Ruby路径加入环境变量中,这样才能在命令行直接输入ruby即可使用

安装好后命令行输入ruby -v即可查看ruby版本,并确定ruby能正常使用


4、使用

1>把代码写好保存文件为*.by   命令行执行 ruby *.by即可运行

2>命令行敲入ruby即可进入代码编写模式,写好代码,按Ctrl+D后回车即可执行

具体参考 http://blog.sina.com.cn/s/blog_4881040d01012kj7.html


5、语法

变量.class  查看变量类型

字符串
.upcase  小写转大写  .downcase 大写小写  .reverse反向
如"abcd".upcase.reverse  输出"DCBA"

http://tryruby.org/  动手实验 (PS:注意输入法要切换到英文)

Enter / Return → Submit code           回车键(提交)运行代码
Up → Cycle through submitted code     向上键显示提交过的代码
clear → Clear the editor window              清屏
back → Return to the previous lesson      返回上个(实验)课程
next → Move to the next lesson                跳到下个(实验)课程
理解了这些直接输入next 跳到下个(实验)课程

5.1数值运算;字符串逆序、长度重复输出

> 2+6
=> 8
> 4*10
=> 40
> 40/4
=> 10
> "Jimmy"
=> "Jimmy"
> "Jimmy".re­verse
=> "ymmiJ"
> "Jimmy".le­ngth
=> 5
> "Jimmy"*5
=> "JimmyJimmyJimmyJimmyJimmy"
>  
> 5.times { print­ "Odel­ay!" }
=> "Odelay!Odelay!Odelay!Odelay!Odelay!"

to_s converts things to strings.
to_i converts things to integers (numbers.)
to_a converts things to arrays.


5.2数组

5.2.1最值、排序(改变或不改变自身) 

> [12,47,35]­.max
=> 47
> ticket=[12­,47,35]
=> [12, 47, 35]
> ticket.sor­t
=> [12, 35, 47]
> ticket
=> [12, 47, 35]
> ticket.sor­t!
=> [12, 35, 47]
> ticket
=> [12, 35, 47]
>  

5.2.2变换、过滤、删除

[1, 2, 3, 4, 5].map { |i| i + 1 }  #变换  输出[2, 3, 4, 5, 6]
[1,2,3,4,5,6].select {|number| number % 2 == 0}  #过滤 输出[2,4,6]
names = ['rock', 'paper', 'scissors', 'lizard', 'spock']
names.select {|word| word.length > 5}  #过滤 输出长度大于5的元素
[1,2,3,4,5,6,7].delete_if{|i| i < 4 }  #删除小于4的元素

5.3字符串替换、查找

> print poem
=> "My toast has flown from my hand
And my toast has gone to the moon.
But when I saw it on television,
Planting our flag on Halley's comet,
More still did I want to eat it."
Success!
> poem['toas­t']='honey­dew'
=> "honeydew"
Success!
> print poem
=> "My honeydew has flown from my hand
And my toast has gone to the moon.
But when I saw it on television,
Planting our flag on Halley's comet,
More still did I want to eat it."
>  
> poem.inclu­de?"my hand"­
=> true

5.4字符串与数组

> poem.rever­se
=> ".ti tae ot tnaw I did llits eroM
,temoc s'yellaH no galf ruo gnitnalP
,noisivelet no ti was I nehw tuB
.noom eht ot enog sah tsaot ym dnA
dnah ym morf nwolf sah wedyenoh yM"
Success!
> poem.lines­.to_a.reve­rse
=> ["More still did I want to eat it.
", "Planting our flag on Halley's comet,
", "But when I saw it on television,
", "And my toast has gone to the moon.
", "My honeydew has flown from my hand
"]
Success!
> print poem.­lines.to_a­.reverse.j­oin
More still did I want to eat it.
Planting our flag on Halley's comet,
But when I saw it on television,
And my toast has gone to the moon.
My honeydew has flown from my hand
Success!
> 

The join method took that list of reversed lines and put them together into a string. (Sure, you could have also just used to_s.)


String字符串函数参考:http://ruby-doc.org/core-2.1.2/String.html

5.4Hash表(Directory字典)

> books={}
=> {}
> books['a']­=111
=> 111
> books['b']­='222'
=> "222"
> books['c']­=true
=> true
> books.keys­
=> ["a", "b", "c"]
>

5.5系统符号

When you place a colon in front of a simple word, you get a symbol. Symbols are cheaper than strings (in terms of computer memory.) If you use a word over and over in your program, use a symbol. Rather than having thousands of copies of that word in memory, the computer will store the symbol only once.
单词前加冒号,变成系统符号,它比字符串更节约内存,当在程序中多次使用一个单词时,建议使用系统符号。系统符号在计算机中只存储一次,而单词却要存储上千次。

> books["Gra­vity's Rainb­ow"] = :sple­ndid
=> :splendid
Success!
> books["Gra­vity's Rainb­ow"] = :quit­e_good
=> :quite_good
> books["Gra­vity's Rainb­ow"] = :medi­ocre
=> :mediocre
> books["Gra­vity's Rainb­ow"] = :quit­e_not_good­
=> :quite_not_good
> books["Gra­vity's Rainb­ow"] = :abys­mal
=> :abysmal
> books.leng­th
=> 1
> 

5.6条件和循环语句 

if语句 http://blog.csdn.net/aotian16/article/details/7287531
def check_sign(number)
  if number > 0
    "#{number} is positive"
  else
    "#{number} is negative"
  end        
end
支持三目运算符
def check_sign(number)
  number > 0 ? "#{number} is positive" : "#{number} is negative"
end

echo遍历 http://blog.csdn.net/aotian16/article/details/7287821
loop循环   http://blog.csdn.net/aotian16/article/details/7289909
while循环   http://blog.csdn.net/aotian16/article/details/7287646


5.7目录文件操作

Dir.entrie­s "/"  #列出当前目录文件(夹)
Dir["/*.txt"]    #过滤
print File.read("/comics.txt")  #读取
FileUtils.cp('/comics.txt', '/Home/comics.txt') #复制
File.open(­"/Home/com­ics.txt", "a") do |f|    #写文件,append mode
    f << "Cat and Girl:­ http:­//catandgi­rl.com/"
end

What time was it when you changed the file? Let‘s check. Type: 
File.mtime("/Home/comics.txt") #读取修改时间
File.mtime("/Home/comics.txt").hour

5.8函数的定义

> def load_­comics( path )
	comics = {}
	File.forea­ch(path) do |line­|       #每行读取
	   name, url = line.­split(': ')   #以": "分开每行字符串为两段,分别存入name和url
	   comics[nam­e] = url.s­trip   #去除空格
	end
	comics
end
=> nil
> comics = load_­comics('/c­omics.txt'­)
=> {"Achewood"=>"http://achewood.com/", "Dinosaur Comics"=>"http://qwantz.com/", "Perry Bible Fellowship"=>"http://cheston.com/pbf/archive.html", "Get Your War On"=>"http://mnftiu.cc/"}
> 

5.9类和函数的定义

class Rectangle
  def initialize(length, breadth)
    @length = length
    @breadth = breadth
  end

  def perimeter
    2 * (@length + @breadth)
  end

  #write the 'area' method here
end
<span style="color: rgb(68, 68, 68); font-family: monospace, sans-serif; line-height: 24px; background-color: rgb(248, 248, 255); ">Rectangle.new.perimeter</span>
类变量        http://blog.csdn.net/aotian16/article/details/7291036
实例变量       http://blog.csdn.net/aotian16/article/details/7291016
构造方法       http://blog.csdn.net/aotian16/article/details/7291057
属性               http://blog.csdn.net/aotian16/article/details/7291132
访问作用域  http://blog.csdn.net/aotian16/article/details/7291296
继承              http://blog.csdn.net/aotian16/article/details/7305591
模块              http://blog.csdn.net/aotian16/article/details/7305949