Monday, March 16, 2020

Comments for Ruby Code (Usage, Single, and Multi-Line)

Comments for Ruby Code (Usage, Single, and Multi-Line) Comments in your Ruby code are notes and annotations meant to be read by other programmers. The comments themselves are ignored by the Ruby interpreter, so the text inside the comments isnt subject to any restrictions. Its usually good form to put comments before classes and methods as well any piece of code that may be complex or unclear. Using Comments Effectively Comments should be used to give background information or annotate difficult code. Notes that simply say what the next line of straightforward code does are not only obvious but also add clutter to the file. Its important to take care not to use too many comments and to be sure the comments made in the file are meaningful and helpful to other programmers. The Shebang Youll notice that all Ruby programs start with a comment that begins with #!. This is called a shebang and is used on Linux, Unix and OS X systems. When you execute a Ruby script, the shell (such as bash on Linux or OS X) will look for a shebang at the first line of the file. The shell will then use the shebang to find the Ruby interpreter and run the script. The preferred Ruby shebang is #!/usr/bin/env ruby, though you may also see #!/usr/bin/ruby or #!/usr/local/bin/ruby. Single-Line Comments The Ruby single-line comment begins with the # character and ends at the end of the line. Any characters from the # character to the end of the line are completely ignored by the Ruby interpreter. The # character doesnt necessarily have to occur at the beginning of  the line; it can occur anywhere. The following example illustrates a few uses of comments. #!/usr/bin/env ruby # This line is ignored by the Ruby interpreter # This method prints the sum of its arguments def sum(a,b)   Ã‚  puts ab end sum(10,20) # Print the sum of 10 and 20 Multi-Line Comments Though often forgotten by many Ruby programmers, Ruby does have multi-line comments. A multi-line comment begins with the begin token and ends with the end token. These tokens should start at the beginning of the line and be the only thing on the line. Anything between these two tokens is ignored by the Ruby interpreter. #!/usr/bin/env ruby begin Between begin and end, any number of lines may be written. All of these lines are ignored by the Ruby interpreter. end puts Hello world! In this example, the code would execute as Hello world!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.