Created
January 16, 2017 15:12
-
-
Save headquarters/eaeea9e74527ca3d039d0945d08425c7 to your computer and use it in GitHub Desktop.
Ruby code snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/ruby | |
| # shebang (#!) must on the first line of the script in order to run this | |
| # with `./script.rb` rather than `ruby script.rb` | |
| # use `whereis ruby` to find the path | |
| # single line comments | |
| =begin | |
| Multi-line comments. | |
| Begin and End must be on the first | |
| column of the file. | |
| =end | |
| heredoc = <<END | |
| A really long | |
| multi-line | |
| string | |
| END | |
| puts heredoc | |
| puts "Hello, World!" | |
| status = true | |
| _new_status = false | |
| status = _new_status | |
| # A constant starts with an uppercase letter. If created outside a class, | |
| # it's available everywhere. Note that it CAN be changed, though! | |
| Legit = true | |
| __not_legit = false | |
| puts "Variables can only start with characters and underscores." | |
| puts "Instance variables start with @, class variables start with @@, and global variables start with $." | |
| # `puts` automatically adds a newline | |
| print "Print does not output newlines automatically" | |
| print ", as puts does." | |
| print "\n" | |
| # print "Give me input: " | |
| # num = gets | |
| # puts "Your input was: " + num | |
| # Object is the parent class of all Ruby classes | |
| # Kernel is a Ruby module, and is included in Object | |
| # A Module is like a class, but you can't instantiate it | |
| # You can add a Module to a Class in order to get access to all its methods | |
| # Types (boolean, integer, float, array, hash) | |
| # Boolean | |
| flag = true | |
| # Integer | |
| num = 3 | |
| # Float | |
| pi = 3.14 | |
| # String | |
| # Single or double quotes work | |
| quote = '"Syntax is the hobgoblin of tiny developer minds -- @cndreisbach."' | |
| # Array | |
| cities = ["Charlotte", "Raleigh"] | |
| # Hash | |
| states = { "NC" => "North Carolina", "SC" => "South Carolina" } | |
| puts "Use kind_of? to see a variable's type. 'pi' is a Float: #{pi.kind_of? Float}" | |
| puts "Use class to see a variable's class: #{cities.class}" | |
| puts "Use inspect to get a string version of an array or hash: #{states.inspect}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment