Ruby学习笔记1(变量,类等)

在Ruby中变量有这么几种:

  • 一般小写字母、下划线开头:变量(Variable)
  • $开头:全局变量(Global variable)
  • @开头:实例变量(Instance variable)
  • @@开头:类变量(Class variable)类变量被共享在整个继承链中
  • 大写字母开头:常数(Constant)

defined?运算符:可以用来测试方法,变量,yield等是否已经定义

Ruby中的双冒号很有意思,本质上是用来定义namespace用的。
当你使用a::b的时候实际是在a这个namespace中寻找b这个常量。这个b有可能是常量,方法和类(方法和类在Ruby中被视为常量)

class Foo
    BAR = "a"
    def initialize
        @bar = "aaaaaaa"
    end
    def aa
        puts @bar
    end

    def self.bb 
        puts BAR
    end
end

puts Foo::BAR     #直接用在类上调用类常量和类方法
puts Foo.new::aa  #实例方法也是常量,但是通常用.来调用
puts Foo.new.aa
puts Foo::bb

另外 :: 在开始位置则表示回到 root namespace ,就是不管前面套了几个 Module ,都算你其实写在最外层。

程序分支控制:
if elsie else end
unless else end
case when when end

while [do] end
begin end while
until [do] end
begin end until

for () in () end

break:终止最内部的循环。如果在块内调用,则终止相关块的方法(方法返回 nil)。
next:跳到循环的下一个迭代。如果在块内调用,则终止块的执行(yield 表达式返回 nil)。
redo:重新开始最内部循环的该次迭代,不检查循环条件。如果在块内调用,则重新开始 yield 或 call。
retry:如果 retry 出现在 begin 表达式的 rescue 子句中,则从 begin 主体的开头重新开始。
如果 retry 出现在迭代内、块内或者 for 表达式的主体内,则重新开始迭代调用。迭代的参数会重新评估。

Dir.entrie­s "/"
=> [".", "..", "Home", "Libraries", "MouseHole", "Programs", "Tutorials", "comics.txt"]

Dir["/*.tx­t"]
=> ["/comics.txt"]

print File.­read("/com­ics.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/
"

FileUtils.­cp('/comic­s.txt','/H­ome/comics­.txt')
=> nil

Dir["/Home­/*.txt"]
=> ["/Home/comics.txt"]

#Turns out, you actually opened a new block when you typed that do keyword.
File.open(­"/Home/com­ics.txt","­a") do |f|
   f<<"Cat and Girl:­http://cat­andgirl.co­m/"
end
=> #<File:/Home/comics.txt (closed)>

print File.­read("/Hom­e/comics.t­xt")
=> "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/
Cat and Girl:http://catandgirl.com/"

File.mtime­("/Home/co­mics.txt"
=> 2016-02-27 05:08:57 UTC

#和python差不多
def load_­comics(pat­h)
..  comics = {}
..  File.forea­ch(path) do |line­|
....    name,url = line.­split(':')­
....    comics[nam­e] = url.s­trip
....    end
..  comics
..  end
=> nil
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值