Tuesday, May 14, 2013

Ruby Lesson 1 Section 3: Writing Good Code

Section Topics: 


  • Single-Line Comments
  • Multi-Line Comments
  • Naming Conventions 

Comments 


To start off, why do we need comments in coding? These are some of the reasons I can think of:



  • Helps explain what the code does
  • Helps other people know what you were trying to do with the code 
  • Helps you remember what you were trying to do with the code 

Single-Line Comments


The '#' symbol is used to start a comment on a line. Anything after the '#' will not show up on the output. Also, '#' loses its effect on the next line. 

Examples: 
  1. Input: print "david" #hello

    Output: david
  2. Input: # print "david"

    Output: (no output)
  3. Input: # print 'david'
              print 'hello'

    Output: hello

Multi-Line Comments


If you don't want to write '#' on each line, as in you want to leave a larger comment you can use '=begin' and '=end'. Unlik methods and setting variables there can be no spaces between the equal sign and either begin or end. If you do have a space Ruby will give you an error.

Both '=begin' and '=end' need to be on its own line.

Example:

  1. Input: =begin
              Hi my name is David.
              This example is to show that =begin and =end can be used for multi-line comments.
              =end

    Output: (no output) 

Naming Conventions 


Conventions is the same as traditions. It's just the way things are done. It doesn't really affect anything, but people do them anyways because that's the way it's always been done. / end rant

Codeacademy starts off with 'local variables', but doesn't really give a definition of what they are. It seems like this is just variables that we set like name="david".

Conventions for local variables:

  • Variables are all in lowercase
  • Underscores '_' are used instead of spaces 
  • Do not start variables with symbols like @ or $ because they are traditionally used for something else

Now, you can go most of these conventions (Ruby doesn't take spaces in variables) and Ruby will still give you your desired output, but the Ruby communittee won't like it, understandable since most people don't like things that are different. I know I'm guilty of it too. 

Well the next section is the review! While codeacademy makes me review things by plugging in code I will use the blog to review what I have learned, how hard it was learning it, and other stuff. 

No comments:

Post a Comment