跳转至内容

Ruby 示例

0% developed
来自 Wikibooks,开放世界中的开放书籍

本书分为多个部分。每个部分都处理一个 Ruby 语言主题,提供从基础到高级的示例。可以在此处找到 Ruby 方法的完整列表。

字符串

[编辑 | 编辑源代码]

示例-001:字符串长度

puts 'That is an object'.size   # => prints 17

示例-002:反转

puts 'This is not a palindrome'.reverse   # => prints 'emordnilap a ton si sihT'

示例-003:单一替换

puts 'a banana'.sub('a', '*')   # => prints '* banana'

示例-004:全局替换

puts 'a banana'.gsub('a', '*')   # => prints '* b*n*n*'

示例-001:使用 times 方法反复运行代码

5.times do
   puts 'Loop'       # => prints 'LoopLoopLoopLoopLoop'
end

示例-002:计算绝对值

puts -10.abs   # => prints 10

示例-001

arr = [['0','0','0'],['0','$','0'],['0','0','0']]
puts arr[1][1]

示例-002

a = [1, 2, 3, 4].shuffle
a.each {|e| puts e}

示例-003

a = %w|this is a string array|
puts a.join(' ')

示例-004

a = (0..10).to_a
a.map! {|x| x**2}
a.each {|e| puts e} # 0, 1, 4, 9, 16...

示例-005

items = ['random', 3, Math::PI, 'items']
puts items.index(3) # 1
puts items.include?(Math::E) # false

哈希表

[编辑 | 编辑源代码]

books = {'978-0140449266' => 'The Count of Monte Cristo',
         '978-0140439243' => 'The Man in the Iron Mask'
}

puts books['978-0140439243']
# The output is 'The Man In The Iron Mask'

more_books = {}
more_books['978-1593081485'] = 'The Three Musketeers'

运算符

[编辑 | 编辑源代码]

:: (作用域运算符)

[编辑 | 编辑源代码]

示例-001

MR_COUNT = 0        # constant defined on main Object class
module Foo
  MR_COUNT = 0
  ::MR_COUNT = 1    # set global count to 1
  MR_COUNT = 2      # set local count to 2
end
puts MR_COUNT       # this is the global constant
puts Foo::MR_COUNT  # this is the local "Foo" constant

示例-002

CONST = ' out there'
class Inside_one
   CONST = proc {' in there'}
   def where_is_my_CONST
      ::CONST + ' inside one'
   end
end
class Inside_two
   CONST = ' inside two'
   def where_is_my_CONST
      CONST
   end
end
puts Inside_one.new.where_is_my_CONST # out there inside one
puts Inside_two.new.where_is_my_CONST # inside two
puts Object::CONST + Inside_two::CONST # out there inside two
puts Inside_two::CONST + CONST # inside two out there
puts Inside_one::CONST # #<Proc:0xedfa98(irb):3> , reference to the procedure
puts Inside_one::CONST.call + Inside_two::CONST # in there inside two

示例-001

a = [1, 2, 3, 4] # array creation
puts a[0] # array indexing
puts a[-1] # same as a[a.length-1]

示例-002

s = 'a meaningless string'
puts s[10] # prints 'e'

示例-003

p = proc {|arg| puts 'You called me with ' + arg.to_s}
p['a string arg'] # same as proc.call







> >= < <=

[编辑 | 编辑源代码]

<=> == === != =~

[编辑 | 编辑源代码]



= ( += -= )

[编辑 | 编辑源代码]



模块和过程

[编辑 | 编辑源代码]


名称、变量、常量和符号

[编辑 | 编辑源代码]

活动记录

[编辑 | 编辑源代码]

套接字

[编辑 | 编辑源代码]

示例-001

# daytimeserver.rb
puts'========================================='
require 'socket'
puts'== daytime server =='
# Open a socket to a local daytime server, read, and print.
print TCPSocket.open('129.6.15.28', 'daytime').read
puts'========================================='

示例-002

# socketmethods.rb
require 'socket'
mySocket = TCPSocket.new( 'www.wikibook.com', 80 )
puts'==================================='
# Returns information on this connection's peer socket as a struct 
# sockaddr packed into a string.
strinfo = mySocket.getpeername 
puts 'strinfo: '+strinfo
# Returns true if query returns numeric address not host name.
puts BasicSocket::do_not_reverse_lookup
puts'==================================='
# Returns information on s as a struct sockaddr packed into a string.
strinfo = mySocket.getsockname 
puts 'strinfo: '+strinfo
puts'==================================='
# Gets the specified socket option.
optval = mySocket.getsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR)
puts 'optval: '+optval.inspect
optval = optval.unpack "i"
puts 'optval: '+optval.inspect
optval = mySocket.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER)
puts 'optval: '+optval.inspect
optval = optval.unpack "ii"
puts 'optval: '+optval.inspect
# Sets reverse_lookup status
BasicSocket::do_not_reverse_lookup=true
# Sets the specified socket option.
mySocket.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
optval = mySocket.getsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR)
puts 'optval: '+optval.inspect
optval = optval.unpack "i"
puts 'optval: '+optval.inspect
puts'==================================='
# 
mySocket.shutdown(2)  # 0 shuts down receiving, 1 sending, and 2 both.
puts 'mySocket: '+mySocket.inspect
puts'==================================='
# Returns true if query returns numeric address not host name.
puts BasicSocket::do_not_reverse_lookup
puts'==================================='
华夏公益教科书