animals = Array.new .push("dog") .push("cow") .sort
# 只有一行的代码块1.times { print "Ruby!" }# 多行代码块1.upto(10) do |x| print x print x + 1end
#!/usr/bin/ruby -w
# coding: utf-8# Emacs用户可以像下面这样写# -*- coding: utf-8 -*-# vi用户可以这样# vi: set fileencoding=utf-8 :
10.times { puts "test".object_id }
# to_s将操作数转换成字符串"Hello planet #" + planet_number.to_s# 但是采用 #{ 和 } 在字符串插入表达式的方式会比用+号更方便,如:"Hello planet ##{planet_number}"
greeting = "Hello"greeting << " World"puts greeting# Outputs "Hello World"
s = "$1000"s.each.char { |x| print "#{x}" }
s = "Ruby"t = st[-1] = ""print s# outputs "Rub"
['a', 'b'] + ['c']# ['a', 'b', 'c']['a', 'b', 'c'] - ['b']# ['a', 'c'][0] * 8# [0, 0, 0, 0, 0, 0, 0, 0]
a = []a << 1 << 2# a is [1, 2]
a = [1, 1, 2, 2, 3, 3, 4]b = [5, 5, 4, 4, 3, 3, 2]a | b# [1, 2, 3, 4, 5]b | a# [5, 4, 3, 2, 1]a & b# [2, 3, 4]b & a# [4, 3, 2]
# 字符串方式numbers = { "one" => 1, "two" => 2 }# 符号方式numbers = { :one => 1, :two => 2 }# Ruby 1.9 支持下面更简洁的表示方式,有点像Jsonnumbers = { one: 1, two: 2 }
a = 0..10b = 'a'..'c'('b'..'d').to_a# ['b', 'c', 'd']# 返回5是否在a的范围内a.member? 5# 返回true
def say_hello(name) result = "Hi, " + name return resultend# ruby可以将方法最后一行的运算结果自动return,所以上面方法还可以简化成def say_hello(name) "Hi, " + nameend
class Person def initialize(name) # 构造函数 @name = name end def say(word) pus "#{word}, #{@name}" #字串相加 endendp1 = Person.new("Bindiry")p1.say("Hello")# 输出Hello, Bindiry
class Person @@name = "Bindiry" def self.say puts @@name endendPerson.say# 输出 Bindiry# 所有的实例变量(@开头)和类变量(@@开头)都只能在类内部访问,外部无法存取# 为了能够读取实例变量,必须定义方法:class Person def initialize(name) @name = name end def name @name end def name=(name) @name = name endendp = Person.new('Bindiry')p.name => "Bindiry"p.name="peny"=> "peny"# 更简洁的实例变量访问方法class Person attr_accessor :nameend# 同样还有只读和只写: attr_reader、attr_writer
类中默认的方法是public的,要设置成private或protected,可以用如下代码:
class MyClass def public_method end private def private_method1 end def private_method2 end protected def protected_method1 end def protected_method2 endend
Ruby中的private和protected和其他语言不太一样,都是可以在整个继承体系中被调用。
class Pet attr_accessor :name, :age def say(word) puts "Say: #{word}" endendclass Cat < Pet def say(word) puts "Meow~" super endendCat.new.say("Hi")
languages = ['Ruby', 'Javascript', 'Perl']languages.each do |lang| puts "I love #{lang}!"end# I Love Ruby# I Love Javascript# I Love Perl
# 重复三次3.times do puts 'Good Job!'end# Good Job!# Good Job!# Good Job!# 从1到9,注:单行可用大括号形式1.upto(9) { |x| puts x }# 使用索引变量languages = ['Ruby', 'Javascript', 'Perl']languages.each_with_index do |lang, i| puts "#{i}, I love #{lang}!"end# 0, I Love Ruby# 1, I Love Javascript# 2, I Love Perl
Module和Class很相似,也是在内部定义方法(Method),只是不能用new来创建,多数被当做命名空间(Namespace)来放一些工具方法。
module MyUtil def self.foobar puts "foobar" endendMyUtil.foobar# 输出 foobar
联系客服