Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

Ruby Code Examples

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

page Ruby on Win Intel x86 / Linux AMD64 Platforms 1.9.2 == This page illustrates the Ruby Code Examples, in a straight way than to lengthy explanations, this can be used like an immediate reference for both syntax and programming ideas. Concise methods attempting a problem with a pragmatic approach are also discussed. Basics Simple I/O puts 'Hi!' # puts the string to stdout print 'ram:' # print does not terminate with default \n at the end of execution name = gets.chomp # read from stdin puts "Hi! #{name}" # interpolates the string, replaces name with its value Strings print 'c:\books\net\apps\tools' # outputs c:\books\net\apps\tools print "c:\books" # outputs books String interpolation allows a variable to get replaced by its value while execution One = 1 puts "#{One} is a number" # outputs, 1 is a number puts "%d is a number" % One # outputs, 1 is a number %Q and %q are string literals that are with special properties puts %Q^ is Quote friendly^ puts %q# you can type "Quotes"!! # # outputs, you can type "Quotes"!! Multiline Strings are defined with '<<' prefix to a named delimiter, like puts <<XYZ Normally programmers try to code to solve the problem and forgets once it is done, but some explore more, to find a concise opproach to the problem, and thats makes him !(repetative) XYZ Ruby is really flexible with strings # choose the one you like ' this ' " this " %/ this / %q{ this } %Q^ this ^ # value => " this " The string delimiter pairs are '', "", but with %, %q and %Q prefix, we have //, {}, ##, as delimiters, the unofficial rule is to use the delimiter that is not used to declare the string itself, this is to declare raw strings to avoid delimiter collision puts %/ '' "" {} ## ^^ / # outputs, '' "" {} ## ^^ Objects An Object is something that can be handled with defined Methods, even for the physical objects around us there are defined methods in using them, whenever we say 'object' it is to mean that it has some methods through which the object can be handled -1.abs # => 1 '1234567'.length # => 7 1234567.to_s.length # => 7 3.times {print 3} # outputs, 333 rand(10).times { |x| puts x } # => random set of numbers from 0 to 10 Ruby is object oriented, everything is an object including numbers, strings and even the nil 1.class # => Fixnum 1.0.class # => Float 'xyz'.class # => String nil.class # => NilClass Enumerators, Ranges, Arrays and Hashes Each of these can use the each method for iteration, though they seems to be synonyms, there is lot of difference in computing, The Enumerators and Ranges are almost of fixed memory length and so are memory efficient and fast, whereas Arrays and Hashes involves complex data structures for to be dynamic Enumerators 5.times.class # => Enumerator 5.upto(10).class # => Enumerator 5.upto(10).next # => 5 Ranges (0...10).class # => Range (0..9).class # => Range (0..2).first # => 0 (0..2).last # => 2 (1..5).next # invalid, Range class doesent have next method (0..3).each { |x| print x } # outputs, 0123 (0...10).reverse_each { |x| print x } # outputs, 9876543210 (-3..3).each.abs { |x| print x } # invalid (-3..3).each { |x| print x.abs } # outputs, 3210123 # Enumerator doesn't require 'each' to iterate 5.upto(10).class # => Enumerator 5.upto(10) { |x| print x } # outputs, 5678910 (5..10).each { |x| print x } # outputs, 5678910 Arrays An array is a collection of elements, by default an array of n elements has its index enumerated from 0 to n-1, i.e, the index to the first element of an array is 0 a = [4,6,7,5] # simple array declaration a.length # => 4 a.rotate # => [6, 7, 5, 4] a.sort # => [4, 5, 6, 7] a.sort.reverse # => [7, 6, 5, 4] a[0] # => 4 a[3] # => 5 a[4] = 3 # => 3 ;resulting array is [4, 6, 7, 5, 3] a << 1 # => [4, 6, 7, 5, 3, 1] ; useful when array size is unknown a[10] = 0 # => 0 ;resulting array is [4, 6, 7, 5, 3, 1, nil, nil, nil, nil, 0] a.length # => 11 array of arrays, array of ranges and arrays of mixed datatypes are allowed to declare, Object Oriented! hex = [(0..9),('A'..'F')] hex.each { |x| x.each { |y| print y }} # outputs, 0123456789ABCDEF # declare an array of arrays nums = [[0,1], [2,3,4,5,6,7], [8,9], ['A','B','C','D','E','F']] binary = nums[0] # => [0, 1] octal = nums[0] + nums[1] # => [0, 1, 2, 3, 4, 5, 6, 7] decimal = nums[0] + nums[1] + nums[2] # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] hexadecimal = nums.flatten # => [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'] octal = (binary + octal).uniq # => [0, 1, 2, 3, 4, 5, 6, 7] a = [0, 1, 2, 3, 4, 5] # array of 6 elements b = a.map { |x| 2**x } # => [1, 2, 4, 8, 16, 32] Hashes Hash is an associative array which is a collections of Keys and it's associated Values capitals = { :france => 'Paris', :England => 'London' } capitals[:westbengal] = 'Kolkata' # append a new element capitals[:karnataka] = 'Bengaluru' # change an element's association Iterators and Blocks Iterators alias chant print 108.times {chant 'Hare Krishna!'} # see the change for yourself Blocks def iterator yield 'yield, ' yield 'blocks,' yield 'Ruby' end iterator {|yeilded| print "use #{yeilded}"} # outputs, use yield, use blocks, use Ruby Ruby programming language 50%