Ruby basics

how to learn ruby

the best way to learn how to code is to actually code. so please go ahead and copy the examples from the github repository that will be provided and follow along the example. Experiment in the editor by typing, by modifying the examples and executing the examples and seeing what happens. That’s the only way to learn how to code.

Ruby basics

Ruby is an Object-Oriented Language

Ruby is a genuine object-oriented language, and pretty much everything in Ruby is an object.

for example the number 5 in ruby is an object of the class called Fixnum

1
2
3
4
irb(main):011:0* 5
=> 5
irb(main):012:0> 5.class
=> Fixnum

flow of control in Ruby

tips:

false and nil objects are false
everthing else is true include 0

triple equal ==> === is called the case equality operator because it is used in precisely this case!
most of the time triple equals just delegates to a double equals, so it’s almost like a super set of a double equals.

3 flavors

  • regular expression
  • double equals
  • comparing the value class

Functions and Methods

  • Technically, a function is defined outside of a class and a method is defined inside a class.
  • In Ruby, every function/method has at least one class it blongs to. Not always written inside a class.

    Methods:

    Methods are invoked by sending a message to an object.

  • Parentheses(“()”) are optional both when defining and calling a method

  • No need to declare type of parameters
  • Can return whatever you want
  • return keyword is optional(last executed line returned)
  • Method names can end with:
    • ‘?’-predicate methods
    • ‘!’-dangerous side-effects
  • Methods can have default arguments

Blocks

  • Chunksof code
    • Enclosed between either curly braces({}) when block content is single line or the keywords do and end when block content spans multiple lines.
    • Passed to methods as last “parameter”
  • Coding with blocks
    • two ways to configure a block in your own method
      • Implicit
        • use `block_given?’ to see if block was passed in
        • use ‘yield’ to “call” the block
      • Explicit
        • use & in front of the last “parameter”
        • use call method to call the block

files

  • read file:
1
2
3
4
5
6
irb(main):001:0> File.foreach('test.txt') do |line|
irb(main):002:1* puts line
irb(main):003:1> p line
irb(main):004:1> p line.chomp
irb(main):005:1> p line.split
irb(main):006:1> end
  • write file

    1
    2
    3
    4
    5
    # override the file
    irb(main):007:0> File.open("test.txt", "w") do |file|
    irb(main):008:1* file.puts "one line"
    irb(main):009:1> file.puts "second line"
    irb(main):010:1> end
坚持原创技术分享,您的支持将鼓励我继续创作!