Sending Email using Ruby – SMTP ”; Previous Next Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers. Ruby provides Net::SMTP class for Simple Mail Transfer Protocol (SMTP) client-side connection and provides two class methods new and start. The new takes two parameters − The server name defaulting to localhost. The port number defaulting to the well-known port 25. The start method takes these parameters − The server − IP name of the SMTP server, defaulting to localhost. The port − Port number, defaulting to 25. The domain − Domain of the mail sender, defaulting to ENV[“HOSTNAME”]. The account − Username, default is nil. The password − User password, defaulting to nil. The authtype − Authorization type, defaulting to cram_md5. An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message. It takes three parameters − The source − A string or array or anything with an each iterator returning one string at a time. The sender − A string that will appear in the from field of the email. The recipients − A string or an array of strings representing the recipients” addressee(s). Example Here is a simple way to send one email using Ruby script. Try it once − require ”net/smtp” message = <<MESSAGE_END From: Private Person <me@fromdomain.com> To: A Test User <test@todomain.com> Subject: SMTP e-mail test This is a test e-mail message. MESSAGE_END Net::SMTP.start(”localhost”) do |smtp| smtp.send_message message, ”me@fromdomain.com”, ”test@todomain.com” end Here, you have placed a basic e-mail in message, using a document, taking care to format the headers correctly. E-mails require a From, To, and Subject header, separated from the body of the e-mail with a blank line. To send the mail you use Net::SMTP to connect to the SMTP server on the local machine and then use the send_message method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren”t always used to route mail). If you”re not running an SMTP server on your machine, you can use the Net::SMTP to communicate with a remote SMTP server. Unless you”re using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider will have provided you with outgoing mail server details that you can supply to Net::SMTP, as follows − Net::SMTP.start(”mail.your-domain.com”) This line of code connects to the SMTP server on port 25 of mail.your-domain.com without using any username or password. If you need to, though, you can specify port number and other details. For example − Net::SMTP.start(”mail.your-domain.com”, 25, ”localhost”, ”username”, ”password” :plain) This example connects to the SMTP server at mail.your-domain.com using a username and password in plain text format. It identifies the client”s hostname as localhost. Sending an HTML e-mail using Ruby When you send a text message using Ruby then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Ruby Net::SMTP provides option to send an HTML message as actual HTML message. While sending an email message you can specify a Mime version, content type and character set to send an HTML email. Example Following is the example to send HTML content as an email. Try it once − require ”net/smtp” message = <<MESSAGE_END From: Private Person <me@fromdomain.com> To: A Test User <test@todomain.com> MIME-Version: 1.0 Content-type: text/html Subject: SMTP e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b> <h1>This is headline.</h1> MESSAGE_END Net::SMTP.start(”localhost”) do |smtp| smtp.send_message message, ”me@fromdomain.com”, ”test@todomain.com” end Sending Attachments as an e-mail To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries. A boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the email. A final boundary denoting the email”s final section must also end with two hyphens. Attached files should be encoded with the pack(“m”) function to have base64 encoding before transmission. Example Following is the example, which will send a file /tmp/test.txt as an attachment. require ”net/smtp” filename = “/tmp/test.txt” # Read a file and encode it into base64 format filecontent = File.read(filename) encodedcontent = [filecontent].pack(“m”) # base64 marker = “AUNIQUEMARKER” body = <<EOF This is a test email to send an attachement. EOF # Define the main headers. part1 = <<EOF From: Private Person <me@fromdomain.net> To: A Test User <test@todmain.com> Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary = #{marker} –#{marker} EOF # Define the message action part2 = <<EOF Content-Type: text/plain Content-Transfer-Encoding:8bit #{body} –#{marker} EOF # Define the attachment section part3 = <<EOF Content-Type: multipart/mixed; name = “#{filename}” Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename = “#{filename}” #{encodedcontent} –#{marker}– EOF mailtext = part1 + part2 + part3 # Let”s put our code in safe area begin Net::SMTP.start(”localhost”) do |smtp| smtp.sendmail(mailtext, ”me@fromdomain.net”, [”test@todmain.com”]) end rescue Exception => e print “Exception occured: ” + e end NOTE − You can specify multiple destinations inside the array but they should be separated by comma. Print Page Previous Next Advertisements ”;
Category: Computer Programming
Ruby – Exceptions
Ruby – Exceptions ”; Previous Next The execution and the exception always go together. If you are opening a file, which does not exist, then if you did not handle this situation properly, then your program is considered to be of bad quality. The program stops if an exception occurs. So exceptions are used to handle various type of errors, which may occur during a program execution and take appropriate action instead of halting program completely. Ruby provide a nice mechanism to handle exceptions. We enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle. Syntax begin # – rescue OneTypeOfException # – rescue AnotherTypeOfException # – else # Other exceptions ensure # Always will be executed end Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control is passed to the block between rescue and end. For each rescue clause in the begin block, Ruby compares the raised Exception against each of the parameters in turn. The match will succeed if the exception named in the rescue clause is the same as the type of the currently thrown exception, or is a superclass of that exception. In an event that an exception does not match any of the error types specified, we are allowed to use an else clause after all the rescue clauses. Example Live Demo #!/usr/bin/ruby begin file = open(“/unexistant_file”) if file puts “File opened successfully” end rescue file = STDIN end print file, “==”, STDIN, “n” This will produce the following result. You can see that STDIN is substituted to file because open failed. #<IO:0xb7d16f84>==#<IO:0xb7d16f84> Using retry Statement You can capture an exception using rescue block and then use retry statement to execute begin block from the beginning. Syntax begin # Exceptions raised by this code will # be caught by the following rescue clause rescue # This block will capture all types of exceptions retry # This will move control to the beginning of begin end Example #!/usr/bin/ruby begin file = open(“/unexistant_file”) if file puts “File opened successfully” end rescue fname = “existant_file” retry end The following is the flow of the process − An exception occurred at open. Went to rescue. fname was re-assigned. By retry went to the beginning of the begin. This time file opens successfully. Continued the essential process. NOTE − Notice that if the file of re-substituted name does not exist this example code retries infinitely. Be careful if you use retry for an exception process. Using raise Statement You can use raise statement to raise an exception. The following method raises an exception whenever it”s called. It”s second message will be printed. Syntax raise OR raise “Error Message” OR raise ExceptionType, “Error Message” OR raise ExceptionType, “Error Message” condition The first form simply re-raises the current exception (or a RuntimeError if there is no current exception). This is used in exception handlers that need to intercept an exception before passing it on. The second form creates a new RuntimeError exception, setting its message to the given string. This exception is then raised up the call stack. The third form uses the first argument to create an exception and then sets the associated message to the second argument. The fourth form is similar to the third form but you can add any conditional statement like unless to raise an exception. Example Live Demo #!/usr/bin/ruby begin puts ”I am before the raise.” raise ”An error has occurred.” puts ”I am after the raise.” rescue puts ”I am rescued.” end puts ”I am after the begin block.” This will produce the following result − I am before the raise. I am rescued. I am after the begin block. One more example showing the usage of raise − Live Demo #!/usr/bin/ruby begin raise ”A test exception.” rescue Exception => e puts e.message puts e.backtrace.inspect end This will produce the following result − A test exception. [“main.rb:4″] Using ensure Statement Sometimes, you need to guarantee that some processing is done at the end of a block of code, regardless of whether an exception was raised. For example, you may have a file open on entry to the block and you need to make sure it gets closed as the block exits. The ensure clause does just this. ensure goes after the last rescue clause and contains a chunk of code that will always be executed as the block terminates. It doesn”t matter if the block exits normally, if it raises and rescues an exception, or if it is terminated by an uncaught exception, the ensure block will get run. Syntax begin #.. process #..raise exception rescue #.. handle error ensure #.. finally ensure execution #.. This will always execute. end Example Live Demo begin raise ”A test exception.” rescue Exception => e puts e.message puts e.backtrace.inspect ensure puts “Ensuring execution” end This will produce the following result − A test exception. [“main.rb:4″] Ensuring execution Using else Statement If the else clause is present, it goes after the rescue clauses and before any ensure. The body of an else clause is executed only if no exceptions are raised by the main body of code. Syntax begin #.. process #..raise exception rescue # .. handle error else #.. executes if there is no exception ensure #.. finally ensure execution #.. This will always execute. end Example Live Demo begin # raise ”A test exception.” puts “I”m not raising exception” rescue Exception => e puts e.message puts e.backtrace.inspect else puts “Congratulations– no errors!” ensure puts “Ensuring execution” end This will produce the following result − I”m not raising exception Congratulations– no errors! Ensuring execution Raised error message can be captured using $! variable. Catch and Throw While the exception mechanism of raise and rescue is great for abandoning the execution when things go wrong, it”s sometimes nice to be able to jump out of some deeply
Ruby – Regular Expressions
Ruby – Regular Expressions ”; Previous Next A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings using a specialized syntax held in a pattern. A regular expression literal is a pattern between slashes or between arbitrary delimiters followed by %r as follows − Syntax /pattern/ /pattern/im # option can be specified %r!/usr/local! # general delimited regular expression Example Live Demo #!/usr/bin/ruby line1 = “Cats are smarter than dogs”; line2 = “Dogs also like meat”; if ( line1 =~ /Cats(.*)/ ) puts “Line1 contains Cats” end if ( line2 =~ /Cats(.*)/ ) puts “Line2 contains Dogs” end This will produce the following result − Line1 contains Cats Regular-Expression Modifiers Regular expression literals may include an optional modifier to control various aspects of matching. The modifier is specified after the second slash character, as shown previously and may be represented by one of these characters − Sr.No. Modifier & Description 1 i Ignores case when matching text. 2 o Performs #{} interpolations only once, the first time the regexp literal is evaluated. 3 x Ignores whitespace and allows comments in regular expressions. 4 m Matches multiple lines, recognizing newlines as normal characters. 5 u,e,s,n Interprets the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. If none of these modifiers is specified, the regular expression is assumed to use the source encoding. Like string literals delimited with %Q, Ruby allows you to begin your regular expressions with %r followed by a delimiter of your choice. This is useful when the pattern you are describing contains a lot of forward slash characters that you don”t want to escape − # Following matches a single slash character, no escape required %r|/| # Flag characters are allowed with this syntax, too %r[</(.*)>]i Regular-Expression Patterns Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | ), all characters match themselves. You can escape a control character by preceding it with a backslash. Following table lists the regular expression syntax that is available in Ruby. Sr.No. Pattern & Description 1 ^ Matches beginning of line. 2 $ Matches end of line. 3 . Matches any single character except newline. Using m option allows it to match newline as well. 4 […] Matches any single character in brackets. 5 [^…] Matches any single character not in brackets 6 re* Matches 0 or more occurrences of preceding expression. 7 re+ Matches 1 or more occurrence of preceding expression. 8 re? Matches 0 or 1 occurrence of preceding expression. 9 re{ n} Matches exactly n number of occurrences of preceding expression. 10 re{ n,} Matches n or more occurrences of preceding expression. 11 re{ n, m} Matches at least n and at most m occurrences of preceding expression. 12 a| b Matches either a or b. 13 (re) Groups regular expressions and remembers matched text. 14 (?imx) Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected. 15 (?-imx) Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected. 16 (?: re) Groups regular expressions without remembering matched text. 17 (?imx: re) Temporarily toggles on i, m, or x options within parentheses. 18 (?-imx: re) Temporarily toggles off i, m, or x options within parentheses. 19 (?#…) Comment. 20 (?= re) Specifies position using a pattern. Doesn”t have a range. 21 (?! re) Specifies position using pattern negation. Doesn”t have a range. 22 (?> re) Matches independent pattern without backtracking. 23 w Matches word characters. 24 W Matches nonword characters. 25 s Matches whitespace. Equivalent to [tnrf]. 26 S Matches nonwhitespace. 27 d Matches digits. Equivalent to [0-9]. 28 D Matches nondigits. 29 A Matches beginning of string. 30 Z Matches end of string. If a newline exists, it matches just before newline. 31 z Matches end of string. 32 G Matches point where last match finished. 33 b Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. 34 B Matches non-word boundaries. 35 n, t, etc. Matches newlines, carriage returns, tabs, etc. 36 1…9 Matches nth grouped subexpression. 37 10 Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code. Regular-Expression Examples Literal Characters Sr.No. Example & Description 1 /ruby/ Matches “ruby”. 2 ¥ Matches Yen sign. Multibyte characters are supported in Ruby 1.9 and Ruby 1.8. Character Classes Sr.No. Example & Description 1 /[Rr]uby/ Matches “Ruby” or “ruby”. 2 /rub[ye]/ Matches “ruby” or “rube”. 3 /[aeiou]/ Matches any one lowercase vowel. 4 /[0-9]/ Matches any digit; same as /[0123456789]/. 5 /[a-z]/ Matches any lowercase ASCII letter. 6 /[A-Z]/ Matches any uppercase ASCII letter. 7 /[a-zA-Z0-9]/ Matches any of the above. 8 /[^aeiou]/ Matches anything other than a lowercase vowel. 9 /[^0-9]/ Matches anything other than a digit. Special Character Classes Sr.No. Example & Description 1 /./ Matches any character except newline. 2 /./m In multi-line mode, matches newline, too. 3 /d/ Matches a digit: /[0-9]/. 4 /D/ Matches a non-digit: /[^0-9]/. 5 /s/ Matches a whitespace character: /[ trnf]/. 6 /S/ Matches non-whitespace: /[^ trnf]/. 7 /w/ Matches a single word character: /[A-Za-z0-9_]/. 8 /W/ Matches a non-word character: /[^A-Za-z0-9_]/. Repetition Cases Sr.No. Example & Description 1 /ruby?/ Matches “rub” or “ruby”: the y is optional. 2 /ruby*/ Matches “rub” plus 0 or more ys. 3 /ruby+/ Matches “rub” plus 1 or more ys. 4 /d{3}/ Matches exactly 3 digits. 5 /d{3,}/ Matches 3 or more digits. 6 /d{3,5}/ Matches 3, 4, or 5 digits. Non-greedy Repetition This matches the smallest number of repetitions − Sr.No. Example & Description 1 /<.*>/ Greedy repetition: matches “<ruby>perl>”. 2 /<.*?>/ Non-greedy: matches “<ruby>” in “<ruby>perl>”. Grouping with Parentheses Sr.No. Example & Description 1 /Dd+/ No group: + repeats d 2 /(Dd)+/ Grouped: + repeats Dd pair 3 /([Rr]uby(, )?)+/ Match “Ruby”, “Ruby, ruby, ruby”, etc. Back References This
Ruby – Date & Time
Ruby – Date & Time ”; Previous Next The Time class represents dates and times in Ruby. It is a thin layer over the system date and time functionality provided by the operating system. This class may be unable on your system to represent dates before 1970 or after 2038. This chapter makes you familiar with all the most wanted concepts of date and time. Getting Current Date and Time Following is the simple example to get current date and time − Live Demo #!/usr/bin/ruby -w time1 = Time.new puts “Current Time : ” + time1.inspect # Time.now is a synonym: time2 = Time.now puts “Current Time : ” + time2.inspect This will produce the following result − Current Time : Mon Jun 02 12:02:39 -0700 2008 Current Time : Mon Jun 02 12:02:39 -0700 2008 Getting Components of a Date & Time We can use Time object to get various components of date and time. Following is the example showing the same − Live Demo #!/usr/bin/ruby -w time = Time.new # Components of a Time puts “Current Time : ” + time.inspect puts time.year # => Year of the date puts time.month # => Month of the date (1 to 12) puts time.day # => Day of the date (1 to 31 ) puts time.wday # => 0: Day of week: 0 is Sunday puts time.yday # => 365: Day of year puts time.hour # => 23: 24-hour clock puts time.min # => 59 puts time.sec # => 59 puts time.usec # => 999999: microseconds puts time.zone # => “UTC”: timezone name This will produce the following result − Current Time : Mon Jun 02 12:03:08 -0700 2008 2008 6 2 1 154 12 3 8 247476 UTC Time.utc, Time.gm and Time.local Functions These two functions can be used to format date in a standard format as follows − # July 8, 2008 Time.local(2008, 7, 8) # July 8, 2008, 09:10am, local time Time.local(2008, 7, 8, 9, 10) # July 8, 2008, 09:10 UTC Time.utc(2008, 7, 8, 9, 10) # July 8, 2008, 09:10:11 GMT (same as UTC) Time.gm(2008, 7, 8, 9, 10, 11) Following is the example to get all the components in an array in the following format − [sec,min,hour,day,month,year,wday,yday,isdst,zone] Try the following − Live Demo #!/usr/bin/ruby -w time = Time.new values = time.to_a p values This will generate the following result − [26, 10, 12, 2, 6, 2008, 1, 154, false, “MST”] This array could be passed to Time.utc or Time.local functions to get different format of dates as follows − Live Demo #!/usr/bin/ruby -w time = Time.new values = time.to_a puts Time.utc(*values) This will generate the following result − Mon Jun 02 12:15:36 UTC 2008 Following is the way to get time represented internally as seconds since the (platform-dependent) epoch − # Returns number of seconds since epoch time = Time.now.to_i # Convert number of seconds into Time object. Time.at(time) # Returns second since epoch which includes microseconds time = Time.now.to_f Timezones and Daylight Savings Time You can use a Time object to get all the information related to Timezones and daylight savings as follows − time = Time.new # Here is the interpretation time.zone # => “UTC”: return the timezone time.utc_offset # => 0: UTC is 0 seconds offset from UTC time.zone # => “PST” (or whatever your timezone is) time.isdst # => false: If UTC does not have DST. time.utc? # => true: if t is in UTC time zone time.localtime # Convert to local timezone. time.gmtime # Convert back to UTC. time.getlocal # Return a new Time object in local zone time.getutc # Return a new Time object in UTC Formatting Times and Dates There are various ways to format date and time. Here is one example showing a few − Live Demo #!/usr/bin/ruby -w time = Time.new puts time.to_s puts time.ctime puts time.localtime puts time.strftime(“%Y-%m-%d %H:%M:%S”) This will produce the following result − Mon Jun 02 12:35:19 -0700 2008 Mon Jun 2 12:35:19 2008 Mon Jun 02 12:35:19 -0700 2008 2008-06-02 12:35:19 Time Formatting Directives These directives in the following table are used with the method Time.strftime. Sr.No. Directive & Description 1 %a The abbreviated weekday name (Sun). 2 %A The full weekday name (Sunday). 3 %b The abbreviated month name (Jan). 4 %B The full month name (January). 5 %c The preferred local date and time representation. 6 %d Day of the month (01 to 31). 7 %H Hour of the day, 24-hour clock (00 to 23). 8 %I Hour of the day, 12-hour clock (01 to 12). 9 %j Day of the year (001 to 366). 10 %m Month of the year (01 to 12). 11 %M Minute of the hour (00 to 59). 12 %p Meridian indicator (AM or PM). 13 %S Second of the minute (00 to 60). 14 %U Week number of the current year, starting with the first Sunday as the first day of the first week (00 to 53). 15 %W Week number of the current year, starting with the first Monday as the first day of the first week (00 to 53). 16 %w Day of the week (Sunday is 0, 0 to 6). 17 %x Preferred representation for the date alone, no time. 18 %X Preferred representation for the time alone, no date. 19 %y Year without a century (00 to 99). 20 %Y Year with century. 21 %Z Time zone name. 22 %% Literal % character. Time Arithmetic You can perform simple arithmetic with time as follows − Live Demo now = Time.now # Current time puts now past = now – 10 # 10 seconds ago. Time – number => Time puts past future = now + 10 # 10 seconds from now Time + number => Time puts future diff = future – past # => 10 Time – Time => number of seconds puts diff This will produce the following result − Thu Aug 01 20:57:05 -0700 2013 Thu Aug 01 20:56:55 -0700 2013
Ruby – Useful Resources
Ruby – Useful Resources ”; Previous Next The following resources contain additional information on Ruby. Please use them to get more in-depth knowledge on this topic. Learn Ruby on Rails online from Scratch 47 Lectures 9.5 hours Eduonix Learning Solutions More Detail Ruby on Rails Course for Beginners 98 Lectures 7.5 hours Skillbakery More Detail Dissecting Ruby on Rails 5 – Become a Professional Developer 228 Lectures 40 hours YouAccel More Detail Print Page Previous Next Advertisements ”;
Ruby – Hashes
Ruby – Hashes ”; Previous Next A Hash is a collection of key-value pairs like this: “employee” = > “salary”. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. The order in which you traverse a hash by either key or value may seem arbitrary and will generally not be in the insertion order. If you attempt to access a hash with a key that does not exist, the method will return nil. Creating Hashes As with arrays, there is a variety of ways to create hashes. You can create an empty hash with the new class method − months = Hash.new You can also use new to create a hash with a default value, which is otherwise just nil − months = Hash.new( “month” ) or months = Hash.new “month” When you access any key in a hash that has a default value, if the key or value doesn”t exist, accessing the hash will return the default value − Live Demo #!/usr/bin/ruby months = Hash.new( “month” ) puts “#{months[0]}” puts “#{months[72]}” This will produce the following result − month month Live Demo #!/usr/bin/ruby H = Hash[“a” => 100, “b” => 200] puts “#{H[”a”]}” puts “#{H[”b”]}” This will produce the following result − 100 200 You can use any Ruby object as a key or value, even an array, so the following example is a valid one − [1,”jan”] => “January” Hash Built-in Methods We need to have an instance of Hash object to call a Hash method. As we have seen, following is the way to create an instance of Hash object − Hash[[key =>|, value]* ] or Hash.new [or] Hash.new(obj) [or] Hash.new { |hash, key| block } This will return a new hash populated with the given objects. Now using the created object, we can call any available instance methods. For example − Live Demo #!/usr/bin/ruby $, = “, ” months = Hash.new( “month” ) months = {“1” => “January”, “2” => “February”} keys = months.keys puts “#{keys}” This will produce the following result − [“1”, “2”] Following are the public hash methods (assuming hash is an array object) − Sr.No. Methods & Description 1 hash == other_hash Tests whether two hashes are equal, based on whether they have the same number of key-value pairs, and whether the key-value pairs match the corresponding pair in each hash. 2 hash.[key] Using a key, references a value from hash. If the key is not found, returns a default value. 3 hash.[key] = value Associates the value given by value with the key given by key. 4 hash.clear Removes all key-value pairs from hash. 5 hash.default(key = nil) Returns the default value for hash, nil if not set by default=. ([] returns a default value if the key does not exist in hash.) 6 hash.default = obj Sets a default value for hash. 7 hash.default_proc Returns a block if hash was created by a block. 8 hash.delete(key) [or] array.delete(key) { |key| block } Deletes a key-value pair from hash by key. If block is used, returns the result of a block if pair is not found. Compare delete_if. 9 hash.delete_if { |key,value| block } Deletes a key-value pair from hash for every pair the block evaluates to true. 10 hash.each { |key,value| block } Iterates over hash, calling the block once for each key, passing the key-value as a two-element array. 11 hash.each_key { |key| block } Iterates over hash, calling the block once for each key, passing key as a parameter. 12 hash.each_key { |key_value_array| block } Iterates over hash, calling the block once for each key, passing the key and value as parameters. 13 hash.each_key { |value| block } Iterates over hash, calling the block once for each key, passing value as a parameter. 14 hash.empty? Tests whether hash is empty (contains no key-value pairs), returning true or false. 15 hash.fetch(key [, default] ) [or] hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can”t be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned. 16 hash.has_key?(key) [or] hash.include?(key) [or] hash.key?(key) [or] hash.member?(key) Tests whether a given key is present in hash, returning true or false. 17 hash.has_value?(value) Tests whether hash contains the given value. 18 hash.index(value) Returns the key for the given value in hash, nil if no matching value is found. 19 hash.indexes(keys) Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found. This method is deprecated. Use select. 20 hash.indices(keys) Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found. This method is deprecated. Use select. 21 hash.inspect Returns a pretty print string version of hash. 22 hash.invert Creates a new hash, inverting keys and values from hash; that is, in the new hash, the keys from hash become values and values become keys. 23 hash.keys Creates a new array with keys from hash. 24 hash.length Returns the size or length of hash as an integer. 25 hash.merge(other_hash) [or] hash.merge(other_hash) { |key, oldval, newval| block } Returns a new hash containing the contents of hash and other_hash, overwriting pairs in hash with duplicate keys with those from other_hash. 26 hash.merge!(other_hash) [or] hash.merge!(other_hash) { |key, oldval, newval| block } Same as merge, but changes are done in place. 27 hash.rehash Rebuilds hash based on the current values for each key. If values have changed since they were inserted, this method reindexes hash. 28 hash.reject { |key, value| block } Creates a new hash for every pair the block evaluates to true 29 hash.reject! { |key, value| block } Same as reject, but changes are made in place. 30 hash.replace(other_hash) Replaces the contents of hash with the
Ruby – Web Applications
Ruby Web Applications – CGI Programming ”; Previous Next Ruby is a general-purpose language; it can”t properly be called a web language at all. Even so, web applications and web tools in general are among the most common uses of Ruby. Not only can you write your own SMTP server, FTP daemon, or Web server in Ruby, but you can also use Ruby for more usual tasks such as CGI programming or as a replacement for PHP. Please spend few minutes with CGI Programming Tutorial for more detail on CGI Programming. Writing CGI Scripts The most basic Ruby CGI script looks like this − Live Demo #!/usr/bin/ruby puts “HTTP/1.0 200 OK” puts “Content-type: text/htmlnn” puts “<html><body>This is a test</body></html>” If you call this script test.cgi and uploaded it to a Unix-based Web hosting provider with the right permissions, you could use it as a CGI script. For example, if you have the Web site https://www.example.com/ hosted with a Linux Web hosting provider and you upload test.cgi to the main directory and give it execute permissions, then visiting https://www.example.com/test.cgi should return an HTML page saying This is a test. Here when test.cgi is requested from a Web browser, the Web server looks for test.cgi on the Web site, and then executes it using the Ruby interpreter. The Ruby script returns a basic HTTP header and then returns a basic HTML document. Using cgi.rb Ruby comes with a special library called cgi that enables more sophisticated interactions than those with the preceding CGI script. Let”s create a basic CGI script that uses cgi − Live Demo #!/usr/bin/ruby require ”cgi” cgi = CGI.new puts cgi.header puts “<html><body>This is a test</body></html>” Here, you created a CGI object and used it to print the header line for you. Form Processing Using class CGI gives you access to HTML query parameters in two ways. Suppose we are given a URL of /cgi-bin/test.cgi?FirstName = Zara&LastName = Ali. You can access the parameters FirstName and LastName using CGI#[] directly as follows − #!/usr/bin/ruby require ”cgi” cgi = CGI.new cgi[”FirstName”] # => [“Zara”] cgi[”LastName”] # => [“Ali”] There is another way to access these form variables. This code will give you a hash of all the key and values − #!/usr/bin/ruby require ”cgi” cgi = CGI.new h = cgi.params # => {“FirstName”=>[“Zara”],”LastName”=>[“Ali”]} h[”FirstName”] # => [“Zara”] h[”LastName”] # => [“Ali”] Following is the code to retrieve all the keys − #!/usr/bin/ruby require ”cgi” cgi = CGI.new cgi.keys # => [“FirstName”, “LastName”] If a form contains multiple fields with the same name, the corresponding values will be returned to the script as an array. The [] accessor returns just the first of these.index the result of the params method to get them all. In this example, assume the form has three fields called “name” and we entered three names “Zara”, “Huma” and “Nuha” − #!/usr/bin/ruby require ”cgi” cgi = CGI.new cgi[”name”] # => “Zara” cgi.params[”name”] # => [“Zara”, “Huma”, “Nuha”] cgi.keys # => [“name”] cgi.params # => {“name”=>[“Zara”, “Huma”, “Nuha”]} Note − Ruby will take care of GET and POST methods automatically. There is no separate treatment for these two different methods. An associated, but basic, form that could send the correct data would have the HTML code like so − <html> <body> <form method = “POST” action = “http://www.example.com/test.cgi”> First Name :<input type = “text” name = “FirstName” value = “” /> <br /> Last Name :<input type = “text” name = “LastName” value = “” /> <input type = “submit” value = “Submit Data” /> </form> </body> </html> Creating Forms and HTML CGI contains a huge number of methods used to create HTML. You will find one method per tag. In order to enable these methods, you must create a CGI object by calling CGI.new. To make tag nesting easier, these methods take their content as code blocks. The code blocks should return a String, which will be used as the content for the tag. For example − #!/usr/bin/ruby require “cgi” cgi = CGI.new(“html4”) cgi.out { cgi.html { cgi.head { “n”+cgi.title{“This Is a Test”} } + cgi.body { “n”+ cgi.form {“n”+ cgi.hr + cgi.h1 { “A Form: ” } + “n”+ cgi.textarea(“get_text”) +”n”+ cgi.br + cgi.submit } } } } NOTE − The form method of the CGI class can accept a method parameter, which will set the HTTP method ( GET, POST, and so on…) to be used on form submittal. The default, used in this example, is POST. This will produce the following result − Content-Type: text/html Content-Length: 302 <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Final//EN”> <HTML> <HEAD> <TITLE>This Is a Test</TITLE> </HEAD> <BODY> <FORM METHOD = “post” ENCTYPE = “application/x-www-form-urlencoded”> <HR> <H1>A Form: </H1> <TEXTAREA COLS = “70” NAME = “get_text” ROWS = “10”></TEXTAREA> <BR> <INPUT TYPE = “submit”> </FORM> </BODY> </HTML> Quoting Strings When dealing with URLs and HTML code, you must be careful to quote certain characters. For instance, a slash character ( / ) has special meaning in a URL, so it must be escaped if it”s not part of the pathname. For example, any / in the query portion of the URL will be translated to the string %2F and must be translated back to a / for you to use it. Space and ampersand are also special characters. To handle this, CGI provides the routines CGI.escape and CGI.unescape. #!/usr/bin/ruby require ”cgi” puts CGI.escape(Zara Ali/A Sweet & Sour Girl”) This will produce the following result − Zara+Ali%2FA Sweet+%26+Sour+Girl”) #!/usr/bin/ruby require ”cgi” puts CGI.escapeHTML(”<h1>Zara Ali/A Sweet & Sour Girl</h1>”) This will produce the following result − <h1>Zara Ali/A Sweet & Sour Girl</h1>” Useful Methods in CGI Class Here is the list of methods related to CGI class − The Ruby CGI − Methods related to Standard CGI library. Cookies and Sessions We have explained these two concepts in different sections. Please follow the sections − The Ruby CGI Cookies − How to handle CGI Cookies. The Ruby CGI Sessions − How to manage CGI sessions. Web Hosting Servers
Ruby – Strings
Ruby – Strings ”; Previous Next A String object in Ruby holds and manipulates an arbitrary sequence of one or more bytes, typically representing characters that represent human language. The simplest string literals are enclosed in single quotes (the apostrophe character). The text within the quote marks is the value of the string − ”This is a simple Ruby string literal” If you need to place an apostrophe within a single-quoted string literal, precede it with a backslash, so that the Ruby interpreter does not think that it terminates the string − ”Won”t you read O”Reilly”s book?” The backslash also works to escape another backslash, so that the second backslash is not itself interpreted as an escape character. Following are the string-related features of Ruby. Expression Substitution Expression substitution is a means of embedding the value of any Ruby expression into a string using #{ and } − Live Demo #!/usr/bin/ruby x, y, z = 12, 36, 72 puts “The value of x is #{ x }.” puts “The sum of x and y is #{ x + y }.” puts “The average was #{ (x + y + z)/3 }.” This will produce the following result − The value of x is 12. The sum of x and y is 48. The average was 40. General Delimited Strings With general delimited strings, you can create strings inside a pair of matching though arbitrary delimiter characters, e.g., !, (, {, <, etc., preceded by a percent character (%). Q, q, and x have special meanings. General delimited strings can be − %{Ruby is fun.} equivalent to “Ruby is fun.” %Q{ Ruby is fun. } equivalent to ” Ruby is fun. ” %q[Ruby is fun.] equivalent to a single-quoted string %x!ls! equivalent to back tick command output `ls` Escape Characters Following table is a list of escape or non-printable characters that can be represented with the backslash notation. NOTE − In a double-quoted string, an escape character is interpreted; in a single-quoted string, an escape character is preserved. Backslash notation Hexadecimal character Description a 0x07 Bell or alert b 0x08 Backspace cx Control-x C-x Control-x e 0x1b Escape f 0x0c Formfeed M-C-x Meta-Control-x n 0x0a Newline nnn Octal notation, where n is in the range 0.7 r 0x0d Carriage return s 0x20 Space t 0x09 Tab v 0x0b Vertical tab x Character x xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F Character Encoding The default character set for Ruby is ASCII, whose characters may be represented by single bytes. If you use UTF-8, or another modern character set, characters may be represented in one to four bytes. You can change your character set using $KCODE at the beginning of your program, like this − $KCODE = ”u” Following are the possible values for $KCODE. Sr.No. Code & Description 1 a ASCII (same as none). This is the default. 2 e EUC. 3 n None (same as ASCII). 4 u UTF-8. String Built-in Methods We need to have an instance of String object to call a String method. Following is the way to create an instance of String object − new [String.new(str = “”)] This will return a new string object containing a copy of str. Now, using str object, we can all use any available instance methods. For example − Live Demo #!/usr/bin/ruby myStr = String.new(“THIS IS TEST”) foo = myStr.downcase puts “#{foo}” This will produce the following result − this is test Following are the public String methods ( Assuming str is a String object ) − Sr.No. Methods & Description 1 str % arg Formats a string using a format specification. arg must be an array if it contains more than one substitution. For information on the format specification, see sprintf under “Kernel Module.” 2 str * integer Returns a new string containing integer times str. In other words, str is repeated integer imes. 3 str + other_str Concatenates other_str to str. 4 str << obj Concatenates an object to str. If the object is a Fixnum in the range 0.255, it is converted to a character. Compare it with concat. 5 str <=> other_str Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is case-sensitive. 6 str == obj Tests str and obj for equality. If obj is not a String, returns false; returns true if str <=> obj returns 0. 7 str =~ obj Matches str against a regular expression pattern obj. Returns the position where the match starts; otherwise, false. 8 str.capitalize Capitalizes a string. 9 str.capitalize! Same as capitalize, but changes are made in place. 10 str.casecmp Makes a case-insensitive comparison of strings. 11 str.center Centers a string. 12 str.chomp Removes the record separator ($/), usually n, from the end of a string. If no record separator exists, does nothing. 13 str.chomp! Same as chomp, but changes are made in place. 14 str.chop Removes the last character in str. 15 str.chop! Same as chop, but changes are made in place. 16 str.concat(other_str) Concatenates other_str to str. 17 str.count(str, …) Counts one or more sets of characters. If there is more than one set of characters, counts the intersection of those sets 18 str.crypt(other_str) Applies a one-way cryptographic hash to str. The argument is the salt string, which should be two characters long, each character in the range a.z, A.Z, 0.9, . or /. 19 str.delete(other_str, …) Returns a copy of str with all characters in the intersection of its arguments deleted. 20 str.delete!(other_str, …) Same as delete, but changes are made in place. 21 str.downcase Returns a copy of str with all uppercase letters replaced with lowercase. 22 str.downcase! Same as downcase, but changes are made in place. 23 str.dump Returns a version of str with all nonprinting characters replaced by nnn notation and all special characters escaped. 24 str.each(separator = $/) { |substr| block } Splits str using argument as the record
Ruby – Quick Guide
Ruby – Quick Guide ”; Previous Next Ruby – Overview Ruby is a pure object-oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan. You can find the name Yukihiro Matsumoto on the Ruby mailing list at www.ruby-lang.org. Matsumoto is also known as Matz in the Ruby community. Ruby is “A Programmer”s Best Friend”. Ruby has features that are similar to those of Smalltalk, Perl, and Python. Perl, Python, and Smalltalk are scripting languages. Smalltalk is a true object-oriented language. Ruby, like Smalltalk, is a perfect object-oriented language. Using Ruby syntax is much easier than using Smalltalk syntax. Features of Ruby Ruby is an open-source and is freely available on the Web, but it is subject to a license. Ruby is a general-purpose, interpreted programming language. Ruby is a true object-oriented programming language. Ruby is a server-side scripting language similar to Python and PERL. Ruby can be used to write Common Gateway Interface (CGI) scripts. Ruby can be embedded into Hypertext Markup Language (HTML). Ruby has a clean and easy syntax that allows a new developer to learn very quickly and easily. Ruby has similar syntax to that of many programming languages such as C++ and Perl. Ruby is very much scalable and big programs written in Ruby are easily maintainable. Ruby can be used for developing Internet and intranet applications. Ruby can be installed in Windows and POSIX environments. Ruby support many GUI tools such as Tcl/Tk, GTK, and OpenGL. Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase. Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts. Tools You Will Need For performing the examples discussed in this tutorial, you will need a latest computer like Intel Core i3 or i5 with a minimum of 2GB of RAM (4GB of RAM recommended). You also will need the following software − Linux or Windows 95/98/2000/NT or Windows 7 operating system. Apache 1.3.19-5 Web server. Internet Explorer 5.0 or above Web browser. Ruby 1.8.5 This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Ruby. It also will talk about extending and embedding Ruby applications. What is Next? The next chapter guides you to where you can obtain Ruby and its documentation. Finally, it instructs you on how to install Ruby and prepare an environment to develop Ruby applications. Ruby – Environment Setup Local Environment Setup If you are still willing to set up your environment for Ruby programming language, then let”s proceed. This tutorial will teach you all the important topics related to environment setup. We would recommend you to go through the following topics first and then proceed further − Ruby Installation on Linux/Unix − If you are planning to have your development environment on Linux/Unix Machine, then go through this chapter. Ruby Installation on Windows − If you are planning to have your development environment on Windows Machine, then go through this chapter. Ruby Command Line Options − This chapter list out all the command line options, which you can use along with Ruby interpreter. Ruby Environment Variables − This chapter has a list of all the important environment variables to be set to make Ruby Interpreter works. Popular Ruby Editors To write your Ruby programs, you will need an editor − If you are working on Windows machine, then you can use any simple text editor like Notepad or Edit plus. VIM (Vi IMproved) is a very simple text editor. This is available on almost all Unix machines and now Windows as well. Otherwise, your can use your favorite vi editor to write Ruby programs. RubyWin is a Ruby Integrated Development Environment (IDE) for Windows. Ruby Development Environment (RDE) is also a very good IDE for windows users. Interactive Ruby (IRb) Interactive Ruby (IRb) provides a shell for experimentation. Within the IRb shell, you can immediately view expression results, line by line. This tool comes along with Ruby installation so you have nothing to do extra to have IRb working. Just type irb at your command prompt and an Interactive Ruby Session will start as given below − $irb irb 0.6.1(99/09/16) irb(main):001:0> def hello irb(main):002:1> out = “Hello World” irb(main):003:1> puts out irb(main):004:1> end nil irb(main):005:0> hello Hello World nil irb(main):006:0> Do not worry about what we did here. You will learn all these steps in subsequent chapters. What is Next? We assume now you have a working Ruby Environment and you are ready to write the first Ruby Program. The next chapter will teach you how to write Ruby programs. Ruby – Syntax Let us write a simple program in ruby. All ruby files will have extension .rb. So, put the following source code in a test.rb file. Live Demo #!/usr/bin/ruby -w puts “Hello, Ruby!”; Here, we assumed that you have Ruby interpreter available in /usr/bin directory. Now, try to run this program as follows − $ ruby test.rb This will produce the following result − Hello, Ruby! You have seen a simple Ruby program, now let us see a few basic concepts related to Ruby Syntax. Whitespace in Ruby Program Whitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in strings. Sometimes, however, they are used to interpret ambiguous statements. Interpretations of this sort produce warnings when the -w option is enabled. Example a + b is interpreted as a+b ( Here a is a local variable) a +b is interpreted as a(+b) ( Here a is a method call) Line Endings in Ruby Program Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as +, −, or backslash at the end of a line, they indicate the continuation of a statement. Ruby Identifiers Identifiers are names of variables, constants, and methods. Ruby identifiers are case sensitive. It means Ram and RAM are two different identifiers in Ruby. Ruby identifier names may consist of alphanumeric characters
Ruby – Classes and Objects
Ruby – Classes and Objects ”; Previous Next Ruby is a perfect Object Oriented Programming Language. The features of the object-oriented programming language include − Data Encapsulation Data Abstraction Polymorphism Inheritance These features have been discussed in the chapter Object Oriented Ruby. An object-oriented program involves classes and objects. A class is the blueprint from which individual objects are created. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. Take the example of any vehicle. It comprises wheels, horsepower, and fuel or gas tank capacity. These characteristics form the data members of the class Vehicle. You can differentiate one vehicle from the other with the help of these characteristics. A vehicle can also have certain functions, such as halting, driving, and speeding. Even these functions form the data members of the class Vehicle. You can, therefore, define a class as a combination of characteristics and functions. A class Vehicle can be defined as − Class Vehicle { Number no_of_wheels Number horsepower Characters type_of_tank Number Capacity Function speeding { } Function driving { } Function halting { } } By assigning different values to these data members, you can form several instances of the class Vehicle. For example, an airplane has three wheels, horsepower of 1,000, fuel as the type of tank, and a capacity of 100 liters. In the same way, a car has four wheels, horsepower of 200, gas as the type of tank, and a capacity of 25 liters. Defining a Class in Ruby To implement object-oriented programming by using Ruby, you need to first learn how to create objects and classes in Ruby. A class in Ruby always starts with the keyword class followed by the name of the class. The name should always be in initial capitals. The class Customer can be displayed as − class Customer end You terminate a class by using the keyword end. All the data members in the class are between the class definition and the end keyword. Variables in a Ruby Class Ruby provides four types of variables − Local Variables − Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more details about method in subsequent chapter. Local variables begin with a lowercase letter or _. Instance Variables − Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name. Class Variables − Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name. Global Variables − Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($). Example Using the class variable @@no_of_customers, you can determine the number of objects that are being created. This enables in deriving the number of customers. class Customer @@no_of_customers = 0 end Creating Objects in Ruby using new Method Objects are instances of the class. You will now learn how to create objects of a class in Ruby. You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods. Here is the example to create two objects cust1 and cust2 of the class Customer − cust1 = Customer. new cust2 = Customer. new Here, cust1 and cust2 are the names of two objects. You write the object name followed by the equal to sign (=) after which the class name will follow. Then, the dot operator and the keyword new will follow. Custom Method to Create Ruby Objects You can pass parameters to method new and those parameters can be used to initialize class variables. When you plan to declare the new method with parameters, you need to declare the method initialize at the time of the class creation. The initialize method is a special type of method, which will be executed when the new method of the class is called with parameters. Here is the example to create initialize method − class Customer @@no_of_customers = 0 def initialize(id, name, addr) @cust_id = id @cust_name = name @cust_addr = addr end end In this example, you declare the initialize method with id, name, and addr as local variables. Here, def and end are used to define a Ruby method initialize. You will learn more about methods in subsequent chapters. In the initialize method, you pass on the values of these local variables to the instance variables @cust_id, @cust_name, and @cust_addr. Here local variables hold the values that are passed along with the new method. Now, you can create objects as follows − cust1 = Customer.new(“1”, “John”, “Wisdom Apartments, Ludhiya”) cust2 = Customer.new(“2”, “Poul”, “New Empire road, Khandala”) Member Functions in Ruby Class In Ruby, functions are called methods. Each method in a class starts with the keyword def followed by the method name. The method name always preferred in lowercase letters. You end a method in Ruby by using the keyword end. Here is the example to define a Ruby method − class Sample def function statement 1 statement 2 end end Here, statement 1 and statement 2 are part of the body of the method function inside the class Sample. These statments could be any valid Ruby statement. For example we can put a method puts to print Hello Ruby as follows − class Sample def hello puts “Hello Ruby!” end end Now in the following example, create one object of Sample class and call hello method and see the result