Ruby语法基础
1.hello world
1 2 3 |
def hello puts "hello ruby" end |
2.String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
a, b = "a double quoted string.\n", %Q|this is also a double quoted string.| b, c = 'a single quoted string', %q{another single quoted string.} d = <<EOF This is a multi-line double quoted string EOF e = %/a string code\n/ f = 'perl rocks' f['perl'] = 'ruby' puts f, f.upcase, f.upcase!, f, f.capitalize puts f.index('r'), f.index('ruby'), f.split, f.reverse, f.next, f.size, f.sub(/[or]/, '*'), f.gsub(/[or]/, '*'), "rub " + f.slice(0..2), "rock " + f.slice(5, 4) g = 2 puts 'g * 3 = #{g * 3}', "g * 4 = #{g * 4}" puts "hello".squeeze, " nice to meet you ".squeeze puts " ruby ".strip, "\t\nruby\trocks\n".strip puts "abcdef".slice(2), "abcdef".slice(2).chr 'a'.upto('z') { |x| print x } |
3.Range
1 2 3 4 5 6 7 8 |
puts (1..10).to_a, (10..1).to_a, (1...10).to_a, ('a'..'z').to_a, ('z'..'a').to_a, ('abc'..'cde').to_a puts (1..10).first, (1..10).last, (1...10).last, (1...10).to_a.last puts (1..10) === 10, (1...10) === 10 for a in 1..10 print a end (1..10).each { |x| print x} (1..10).step(2) {|x| print x} |
4.Numberic
1 2 3 4 5 6 7 8 9 |
puts (2**30).class, (-2**30).class puts (2**30 -1).class, (-2**30-1).class puts -1.9.class puts "Hex " + 0x15 puts "Octal " + 015 puts "Binary " + 0b1101 puts 1.next, 1.8.floor,1.3.ceil, 1.8.ceil, 1.8.floor, 2.3.truncate, 2.8.truncate, 2.3.round, 2.8.round, -2.3.abs puts "A B " , 65.chr, 66.chr 1.upto(9) {|x| print x} |
5.Array
1 2 3 4 5 |
a = Array.new, b = [] b = [1, 'a', '3', [1,2,3], :ruby, /rocks/, {:ruby => 'rocks'}] c = %w(1 b 23 d 4) e = [1,2,3,4,5], a[1..3], a[1...3], a.slice(1..3), a.slice(1,3), a[-2], a.size, a.first, a.last, a.slice(1), a.fill(1) f = [1,2,3,4,5,6,1,2,3], f.reverse, f.sort, f.uniq, f.uniq!, f.unshift 'ruby', f.shift, f.push 'rocks', f.pop, f.insert(2, 'hello'), f.delete('hello'), f.join('-'), f.join('-').split('-'), f.each {|x| print x }, f.map {|x| x * 2}, f.collect {|x| x * 2}, f.select {|x| x > 2}, f.find {|x| x > 4 }, f.find_all {|x| x > 4}, f.reject {|x| x < 2}, f.detect {|x| x > 5}, f.inject {|sum + n| sum + n}, f.inject(5) {|sum, n| sum + n} |
6.Hash
1 2 3 4 |
a = {1 => 'a', 'b' => 2}, a[1], a['b'], a.size, a.invert
b = {1 => 'a', 2 => 'b', 3 => 'c'}, a.each {|key, value| puts "#{key} = #{value}"}, a.each_key {|key| puts "key: #{key}"}, a.each_value {|value| puts "value: #{value}"}
c = {1 => 'a', 2 => 'b', 3 => 'c'}, c[3] = 'e', c[4] = 'd', a.shift, a.inspect, a.delete 3, a.inpect
d = c.reject {|key, value| value == 'b' }, d.inject, d.merge({1 => 'A', 3 => 'C', 4 => 'd'}), d.inspect |
7.Symbol
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
3.times { puts "ruby".object_id }, 3.times { puts :ruby.object_id}, 3.times { puts 12345.object_id} class A attr_accessor :name end a = A.new, a.name, a.name = 'ruby', a.name class B def name @name end def name=(name) @name = name end end b = B.new, b.name, b.name = 'ruby', b.name c = %w{aa, bb, cc, dd), d = c.map{|x| x.send(:capitalize)}, e = c.map{|x| x.capitalize} |
8.Regexp
1 2 3 4 5 6 |
/^abc/ === 'abcdef', /^abc/ === 'defabc', /abc$/ === 'defabc' /abc/ =~ '012abc678', /abc/ =~ '012345678', 'yyy' =~ /^y/i, 'wwwyyy' =~ /^y/i "I love ruby".sub(/[aeiou]/, '*') "I love ruby".gsub(/[aeiou]/, '*') "I love ruby".sub(/[aeiou]/i, '*') "I love ruby".gsub(/[aeiou]/i, '*') |
9.Conditional
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 29 |
a = 10 if a > 0 puts 'a > 0' elsif a < 0 puts 'a < 0' else puts 'a == 0' end str = if a > 0 then 'a > 0' elsif a < 0 then 'a < 0' else 'a == 0' end puts str puts 'a == 10' unless a != 10 case a when 0 puts 'a == 0' when 10 puts 'a == 10' else puts 'Unknown' end str = case a when -10..0 then '-10 < a < 0' when 0 then 'a == 0' when 1..20 then '1 < a < 20' else 'Unknown' end puts str |
10.Loop
1 2 3 4 5 6 7 8 9 10 |
a = 1 a *= 2 while a < 10, puts a a -= 2 while a < 0, puts a 3.times do print 'ruby ' end for x in (1..3) puts 'ruby rocks' end 3.times { puts 'ruby rocks'} |
11.Exception
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 29 30 31 32 |
begin 5 / 0 rescue puts "Oops!" else puts "Congratulations! No errors." ensure puts "Here we go." end begin 5 / 1 rescue puts "Oops!" else puts "Congratulations! No errors." ensure puts "Here we go." end a = -1 begin if a < 0 raise 'a < 0!' end rescue RuntimeError => e puts e else puts "Congratulation! No errors." ensure puts 'Here we go." end |
12.Class
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 29 30 31 32 |
class A def hello(people) puts "Hi, #{people}!" end end a = A.new a.hello 'Matz' class People def initialize(name, age) @name = name @age = age end def to_s "name = #{@name}, age = #{@age}" end end ruby = People.new('Ruby', 16) puts ruby class Teacher < People def initialize(name, age, gender) super(name, age) @gender = gender end def to_s super + ", gender => #{@gender}" end end lisa = Teacher.new('Lisa', 28, 'female') |
13.Method
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 29 30 31 32 |
class A def instance_method 'instance_method' end def self.class_method1 'class_method1' end def A.class_method2 'class_method2' end def << self def class_method3 'class_method3' end end end A.new.instance_method A.class_method1 A.class_method2 A.class_method3 def takeBlock(p) if block_given? yield(p) else puts p end end takeBlock 'a' takeBlock('a') {|x| puts '+' * 10 + x} |
14.AccessControl
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 29 30 31 32 33 34 35 36 37 38 39 40 |
class A def public_method end public def public_method1 end def public_method2 end protected def protected_method1 end def protected_method2 end private def private_method1 end def private_method2 end end class B def method1 end def method2 end def method3 end def method4 end def method5 end def method6 end public :method1, :method2 protected :method3, :method4 private :method5, :method6 end |
15.Module
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
module A def say "hello ruby" end end a = A.new rescue "module can't be instantiated" class B include A def test 'test' end end b = B.new b.say b.test class C class << self include A end end |
16.Proc
1 2 3 4 5 6 7 8 9 10 11 12 |
greeting = Proc.new {|someone| "Hi, #{someone}"} greeting.call("ruby") def add(m) return Proc.new {|n| n + m } end add10 = add(10) add100 = add(100) add10.call(40) add100.call(400) |
Wiki首页 | 查看所有 | 编辑 | 输出到博客 | 历史版本