Ruby基础

1、数组和散列表
a = ['ant', 'bee', 'cat', 'dog']

a = %w{ant bee cat dog}

inst_section = {
    'cello'    => 'string',
    'clarinet'  => 'woodwind',
    'drum'      => 'percussion',
    'oboe'      => 'woodwind'
}

$greeting = "Hello world" #全局变量
2.block的使用
['cat', 'dog', 'horse'].each {|name| print name}

3.times {print 'i'} # 0,1,2

3.upto(6) {|i| print i} #3,4,5,6

('a'..'e').each {|char| print char}
##############如何调用block#####################
def call_block
  puts "begin the method"
  yield("hello", 1)
  yield("hello", 2)
  puts "end the method"
end

call_block {|greet, time| puts "#{greet}, #{time}"}
#begin the method
#hello, 1
#hello, 2
#end the method
################################################

def block_test
  if block_given? #函数后面给block了
    yield "give the block"
  else
    puts "give no block"
  end
end 

##############block其他方式########################
def call_block(&block)
  block.call
end
#&代表的是块转变为Proc(block to proc conversion)
call_block {puts "block的另一种调用"}

p = Proc.new {puts "block的其他调用"}
call_block(&p)

##################map函数用法#####################
name_list = ["chareice", "angel"]
name_list.map(&:upcase)  # => ["CHAREICE", "ANGEL"]

3.类

class Song
  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end
  def to_s
    "Song : #{@name}--#{@artist} (#{@duration})"
  end
end

song = Song.new("Bicy", "Fleck", 260)
puts song.to_s
继承
class KaraokeSong < Song
  def initialize(name, artist, duration, lyrics)
    super(name, artist, duration)
    @lyrics = lyrics
  end

  def to_s
    super + "[#@artist]"
  end
end
get方法
  def name
    @name
  end
  def artist
    @artist
  end
  def duration
    @duration
  end
get更简单的方式
  attr_reader :name, :artist, :duration
set方法
  def duration=(new_duration)
    @duration = new_duration
  end
set更简单的方法
  attr_writer :duration

4.类方法

class SongList
  MAX_TIME = 5 * 60
  
  def SongList.is_too_long(song)
    return song.duration > MAX_TIME
  end
end

5.单例模式

class MyLogger
  private_class_method :new  #private的类方法
  @@logger = nil
  def Mylogger.create  #def self.create
    @@logger = new unless @@logger
    @@logger
  end
  
  class <<self #类方法的第三种方式
    def create
      @@logger = new unless @@logger
      @@logger
    end
  end
end

⬆对比private_class_method

class MyTest
  def print_hello
    puts "hello"
  end

  private :print_hello #private实例方法
end

6.类的访问控制

在Ruby中对象的方法默认是public,Ruby中一切都是对象,对象之间赋值采用的是引用传递

7.容器类

数组
a = [1, 3, 5, 7, 9]

a[1, 3]  ->[3, 5, 7]

a[1..3]  ->[3, 5, 7]

a[1...3]  ->[3, 5]

8.实现管理song的容器

class SongList
  def initialize
    @songs = Array.new
  end

  def append(song)
    @songs.push song
    self
  end

  def delete_first
    @songs.shift
  end

  def delete_last
    @songs.pop
  end
  
  def [](index)
    @songs[index]
  end
end
实现查找
def with_title
    @songs.find {|song| title == song.name}
end
#查找到第一个就返回
inject方法
[1, 3, 5, 7].inject(0) {|sum, element| sum+element}

[1, 3, 5, 7].inject(1) {|product, element| product * element]

block做闭包回调

class Button
  def initialize(label, &action)
    @action = action
    @label = label
  end

  def button_pressed
    @action.call(self)
  end
end

button = Button.new("play") {puts 'play the music'}
#将后面的block传给&action
常见的迭代器
3.times {print "X "}
1.upto(5) {|x| print x, " "}
(1..5) {|x| print x}
99.downto(90) {|x| print x, " "}
50.step(80, 5) {|x| print x, " "}

document生成字符串

string = <<END_OF_STRING
  The body of the string
  is the input lines up to
  one ending with the same text '<<'
END_OF_STRING
字符串处理
#chomp去除行末的换行符
file, length, name, title= string.chomp.split(/\s*\|\s*/)
name.squeeze!(" ") #去除多余的空格,留一个(!),不带!空格全去除

区间

digits = 0..9
puts digits.include?(5)
puts digits.min
puts digits.max
puts digits.reject {|i| i<5}
digits.each {|digit| print digit}

(0..9).to_a

正则表达式

a = Regexp.new('^\s*[a-z]')

if line =~ /perl|python/
  puts "Scripting language mentioned:#{line}"
end
匹配之后Ruby会设置一些变量
$& ->模式匹配的那部分字符串
$` -> 匹配之前的那部分字符串
$' -> 匹配之后的那部分字符串

不定参数

def log(*infos)
  infos.each {|info| puts info}
end

符号和字符串

"name".to_sym()       #:name
:name.to_s()             #"name"

类型判断

:name.is_a?(Symbol) #true
"name".is_a?(String) #true

重磅方法

带"!"方法返回的对象本身,普通方法返回的是对象的拷贝
9. 对象的内存
per1 = "Tim"
per2 = per1 #别名
per1[0] = 'J'    #per2 == "Jim"
per1 = "Tim"
per2 = per1.dup #复制
per1[0] = 'J'
per1  -> "Jim"
per2 -> "Tim"
per = "Tim"
per.freeze
per[0] = 'J'  #raise a TypeError

10. 计算数组的维度

module ObjectExtension
  refine Object do
    def dimension
      return 0 if self.class != Array || self.empty?
      max = 0
      self.each do |a|
        t = a.dimension
        max = [max, t].max
      end
      max + 1
    end
  end
end

using ObjectExtension

puts [1,[124,4], [1,2,3]].dimension
11. 技巧
songDuration = "2:58"
mins, secs = songDuration.split(/:/)
mins, secs = songDuration.scan(/\d+/)
12. 可选参数
#params={}可以替换成**params
def advance_search(key_words, params={})
  default_params = {
    page: 1,
    paging_size: 20,
    mode: 'text'
  }
  params = default_params.merge params

  puts params
end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,277评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,689评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,624评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,356评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,402评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,292评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,135评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,992评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,429评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,636评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,785评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,492评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,092评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,723评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,858评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,891评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,713评论 2 354

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,625评论 18 399
  • 按照以往的学习方式,每学一种编程语言都要先配置它的环境。因此,在正式写 Ruby 程序之前应该先配置环境。看这里,...
    芝麻香油阅读 412评论 0 1
  • ruby基础用法简单整理 基础变量部分 变量声明 支持并行赋值 变量操作 变量交换 语句后面不跟";" / % 字...
    owlwisp阅读 1,181评论 0 51
  • 孩子,你以为你向生活妥协了;生活就会让你过得很美好。其实不然,我告诉你好了;如果你向生活妥协;生活只会更加肆无忌惮...
    蜕变ING阅读 215评论 0 0
  • 我走时裹着一团云烟 我又来了,乘着月色 树影松梦,鸟儿高眠 一切都是熟睡的模样 月亮走过大地,我走过月光 荒草寂静...
    琴键上跳舞的米老鼠阅读 211评论 2 11