Ruby Language Overview
Ruby Basic Concepts
Ruby Console (Interactive Ruby): irb
Syntax
Assignment
Modules and Classes
Related methods in Ruby can be packaged in modules.
Modules are often explicitly imported or they can be imported automagically in frameworks that favours conventions like ruby on rails.
module ApplicationHelper
# ....
end
Method definition
By convention, every method that ends with a question mark ?
returns a boolean value.
irb(main):> "".empty?
=> true
Defining a method with def
:
def message(str = '')
return "empty string!" if str.empty?
return "nonempty."
end
Comments
Comments start with the hash mark #
(also called the pound sign and the octothorpe)
# This is a comment in ruby
Local variable assignment
Booleans
Comparisons
- Equality comparison operator
==
- Not equal comparison operator
!=
Control flow
- Control Expressions http://ruby-doc.org/core-2.3.1/doc/syntax/control_expressions_rdoc.html
Conditional clause (if)
if-elsif-end
irb(main):> if "".empty? && !"a".empty? || "".length==0 irb(main):> puts "YOLO" irb(main):> elsif !"".empty? irb(main):> puts "That is not YOLO" irb(main):> end YOLO => nil irb(main):> puts "Hello" if "".empty? Hello => nil
Strings
Strings in Ruby are specified with double quotes "a string"
or single quotes'another string'
.
The main difference between them is that double quotes allows string interpolation "Hello #{name}"
and escape sequences "\n"
so it is encouraged to use them.
String concatenation is done with +
sign: "foo" + "bar"
or with interpolation:
irb(main):> sport="running" => "running" irb(main):> "keep #{sport}" => "keep running"
Printing
To print a string there is the command puts
and print
.
The command puts
stands for put string and is used to print strings.
puts
includes a new line after showing the content and does not
return anything (__nil__).irb(main):> print "foobar" foobar=> nil irb(main):> puts "foobar" foobar => nil irb(main):> print "foobar\n" foobar => nil
Return values
Data structures
Arrays
a = ["foo", "bar", "baz"]
- Access specific array position
a[0]
a.first
Operator precedence
References
- Official Documentation https://www.ruby-lang.org/
- Docs and API http://ruby-doc.org/
- Double Versus Single Quotes In RubyAugust 9, 2016
- Ruby Language Overview
- What Is The Difference Between Modules And Classes In RubyAugust 9, 2016
- Managing Ruby Gems Version For Each ProjectJune 10, 2016
Articles
Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.
Powered by SimpleIT Hugo Theme
·