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

来源:互联网 发布:手机找不到wifi网络 编辑:程序博客网 时间:2024/06/10 16:29

在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    endendputs Foo::BAR     #直接用在类上调用类常量和类方法puts Foo.new::aa  #实例方法也是常量,但是通常用.来调用puts Foo.new.aaputs 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.htmlGet Your War On: http://mnftiu.cc/"FileUtils.­cp('/comic­s.txt','/H­ome/comics­.txt')=> nilDir["/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.htmlGet 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