Sunday, July 28, 2019

Getting started with Ruby (on Rails)

Ruby language basics

  • Ruby in 20 minutes
    •  the Ruby REPL is irb
    • expressions in a string are escaped with "#{expression}"
    • print function is puts
    • functions are defined like:
      def myfun(somearg = "default")
        # do something with somearg
      end
      • arguments can have default value
      • functions can be called like:
        myfun
        myfun()
        myfun "some other arg"
        myfun("some other arg")
    • classes are defined like:
      class MyClass
        attr_accessor :somearg
        def initialize(somearg = "default")
          @somearg = somearg
        end
        # do something with @somearg anywhere in the class
      end
      • class instantiation is done with the "new" keyword:
        myclass = MyClass.new("some other arg")
      • the instance variable @somearg is private
      • the methods defined in the class are public by default
      • the attribute accessor :somearg allows to get and set the instance variable (public). Usage: myclass.somearg and myclass.somearg= "something new"
    • information about a class can be retrieved with MyClass.instance_methods(show_inherited = true)
    • iterations
      • for each loop
        @names.each do |name|
          puts "Hello #{name}!"
        end
    • conditionals
      • if-else block
        def say_bye
          if @names.nil?
            puts "..."
          elsif @names.respond_to?("join")
            # Join the list elements with commas
            puts "Goodbye #{@names.join(", ")}.  Come back soon!"
          else
            puts "Goodbye #{@names}.  Come back soon!"
          end
        end
Some additional info:

Ruby on Rails basics

rspec testing framework basics

...coming up...
in the meantime here are some resources:


My IDE choice

No comments:

Post a Comment