Download presentation
Presentation is loading. Please wait.
1
17-Jun-15 Assorted Ruby Details
2
The command line irb starts an interactive Ruby interpreter ruby starts Ruby, with input from the command line End with an end-of-file character ( ^D or F6 ) Not actually very useful ruby filename.rb executes the given file ruby -e quotedString executes the quoted string Example: ruby -e 'puts "The time is #{Time.now}" ' ruby -v tells you Ruby’s version number On Unix, if the first line of a Ruby file is #!/usr/bin/ruby (or wherever ruby is located), the file can be executed by just entering the file name
3
Adding and removing methods def adds a method; undef removes a method The only parameter to undef is the method name To add an instance method, first “open” the class Example: class String; def nchars; length; end; end There are several ways to add a class method to a class def Person.species; 'human'; end Within the Person class, you can use def self.species You can add a method to individual objects def oscar.mood; 'grouchy' ; end
4
Numbers Numbers may be written in decimal, hexadecimal, octal, or binary Decimal: 3405691582 Hex: 0xCAFEBABE or 0XCAFEBABE Octal: 031277535276 or 0o31277535276 Binary: 0b11001010111111101011101010111110 or 0B etc. For readability, numbers may contain (but not begin or end with) underscores Examples: 3_405_691_582, 0b_111_101_101 Integers may be indexed to retrieve their bits Example: 5.step(0, -1) { |i| print 6[i] } 000110
5
printf and friends printf format_string, value, …, value Formats are % length code for most things, % length.fractional_digits code for floats %d decimal, %o octal, %x hex, %b binary, %f float, %s string Negative lengths mean left justified Various other controls Example: printf "pi = %8.4f", 3.14159 2 pi.=…3.1416 The (equivalent) methods sprintf and format take the same parameters as printf, but return the resultant string rather than printing it
6
Some File < IO methods gets – get a line of text getc – get a character of text (as ASCII; use.chr ) ungetc – put back a character pos – the current character position in the input stream lineno – the number of times gets has been called pos= – move to the given position in the file rewind – move to the beginning of the file readlines – read the stream as an array of strings write( string ), print( string ), <<( string ) – write at the current position eof? – test if at the end of file closed? – test if the file has been closed
7
Some File methods rename( oldname, newname ) – rename a file read( filename ) – read the entire file as a single string readlines( filename ) – read the entire file as an array of strings open( filename ) – with no block, a synonym for File.new with a block, the file is passed to the block, and automatically closed when the block finishes exists?( filename ) – test if a file with that name exists writable?( filename ) – test if the file can be written directory?( filename ) – test if the file is a directory zero?( filename ) – test if the file is empty size( filename ) – returns the size of the file mtime( filenam e) – returns the modification time of the file
8
Streams The following constants refer to standard I/O streams: STDIN, STDOUT, STDERR The following variables are initially set to the corresponding constants: $stdin, $stdout, $stderr In addition, $defout (initially equal to $stdout ) is where output with no specified destination is sent
9
Some String methods ljust( length ), center( length ), rjust( length ) – left justify, center, or right justify the string by padding with spaces downcase, upcase, swap, capitalize – modify capitalization include?( s_or_c ) – tests whether the string includes the given string or character index( s_or_c [, offset ]) – returns the index after offset(or nil ) at which the gives string starts rindex( s_or_c [, limit ]) – returns the last index (before limi t ), or nil, at which the string starts
10
Some more String methods strip – remove leading and trailing spaces chop – remove the last character (also chop! is destructive) chomp – remove the last character if it is a newline (also chomp! ) tr( chars, replacement ) – replace the characters in chars with the corresponding characters in replacement; accepts ch1-ch2 notation
11
Some Array methods min, max – return the smallest or largest element uniq – return an array with no duplicate elements compact – return an array with no nil elements sort – return a sorted array & – perform an intersection (only elements in both) | – perform a union (elements in either) grep( regexp) – return elements matching the pattern push( element) – add the element to the end of the array pop – remove and return the last element shift – remove and return the first element
12
Chaining Nondestructive methods can usually be chained Example: x = gets.chomp.strip.downcase Many destructive methods return nil if they make no changes in the receiver, hence cannot be chained Example: x = gets.chomp!.strip!.downcase! will result in a runtime error
13
Iterators In Ruby, loops are considered low-level, to be used only when there is no appropriate iterator collection.each – step through every element n.times – do a block n times n.downto( limit ) – step from n down to and including limit n.upto( limit ) – step from n up to and including limit string.each_line – get each line from a string string.each_char – get each character (as an integer) from a string
14
More iterators collection.each_index – iterate over the indices of a collection collection.each_with_index – iterate over the values in a collection, along with their indices Example: lineup.each_with_index { |man, pos| print pos, man } hash.each_key – iterate over keys hash.each_value – iterate over values hash.each_pair – iterate over key-value pairs collection.select { | v | condition } – choose only items that meet the condition collection.map { | v | transformation } – create a new collection with the transformation applied to each item
15
The End
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.