Jump to content

Ruby By Examples

0% developed
From Wikibooks, open books for an open world

The book is broken down into sections. Each section deals with a Ruby language theme, giving examples, from basic to advanced. A full list of Ruby methods can be found here.

Basics

[edit | edit source]

Strings

[edit | edit source]

Example-001: String Length

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

Example-002: Reversing

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

Example-003: Single substitution

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

Example-004: Global substitution

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

Numbers

[edit | edit source]

Example-001: Use the times method to run code over and over

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

Example-002: Calculating absolute value

puts -10.abs   # => prints 10

Arrays

[edit | edit source]

Example-001

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

Example-002

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

Example-003

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

Example-004

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

Example-005

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

Hashes

[edit | edit source]

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'

Operators

[edit | edit source]

:: (Scope Operator)

[edit | edit source]

Example-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

Example-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

Example-001

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

Example-002

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

Example-003

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


+ - ! ~

[edit | edit source]

* / %

[edit | edit source]

<< >>

[edit | edit source]



> >= < <=

[edit | edit source]

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

[edit | edit source]


.. ...

[edit | edit source]

= ( += -= )

[edit | edit source]


and or

[edit | edit source]

Intermediate

[edit | edit source]

Modules and Procedures

[edit | edit source]

Classes and Methods

[edit | edit source]

Names, Variables, Constants and Symbols

[edit | edit source]

Advanced

[edit | edit source]

Active record

[edit | edit source]

Sockets

[edit | edit source]

Example-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'========================================='

Example-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'==================================='