Maciej Mensfeld
twitter: @maciejmensfeld
www: mensfeld.pl
e-mail: maciej@mensfeld.pl
Ruby is a powerful, flexible programming language you can use in web/Internet development, to process text, to create games, and as part of the popular Ruby on Rails web framework.
www.codecademy.com
public class HelloWorld{
public static void main(String[] args){
System.out.println("Hello World");
}
}
vs
puts "Hello World"
3.times { puts "Ruby is cool" }
["Maciek", "John", "Anna"].first #=> "Maciek"
["Maciek", "John", "Anna"].last #=> "Anna"
attr_accessor :name
"Anna".class #=> String
nil.class #=> NilClass
1.class #=> Integer
{}.class #=> Hash
[].class #=> Array
self.class #=> Object
(0..9).class #=> Range
# Comments start with "#"
class Messenger
def initialize(name)
# Instance variables start with "@"
@name = name
end
# Methods are public by default
def hello
puts "Hello #{@name}!"
end
end
execution:
msg = Messenger.new("Maciek")
msg.hello #=> "Hello Maciek!"
# Ruby each loop
friends.each{ |friend| puts friend }
// Same in C
for(i = 0; i < number_of_elements; i++)
{
print element[i];
}
10.times { |i| puts i }
10.downto(1) { |i| puts i }
A Ruby symbol is a thing that has both a number (integer) representation and a string representation.
# Symbols are used in many places,
# for example you can use them to create hashes
user = { name: 'Maciej', email: 'maciej@mensfeld.pl' }
print user[:name] #=> "Maciej"
Symbols are way more efficient than strings because they act like singletons.
puts "name".object_id # => 8305060
puts "name".object_id # => 8295440
puts :name.object_id # => 85148
puts :name.object_id # => 85148
puts "name".object_id == "name".object_id # => false
puts :name.object_id == :name.object_id # => true
If you need a certain functionality, someone probably built it already!
RubyGems is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries (in a self-contained format called a "gem"), a tool designed to easily manage the installation of gems, and a server for distributing them.
Ruby on Rails is great, but there's much more than that!
gem install sinatra
# app.rb
require 'sinatra'
class HelloWorldApp < Sinatra::Base
get '/' do
'Hello, world!'
end
end
# config.ru
require './app'
run HelloWorldApp
rackup
# Puma 2.11.3 starting...
# * Min threads: 0, max threads: 16
# * Environment: development
# * Listening on tcp://localhost:9292
Maciej Mensfeld
twitter: @maciejmensfeld
www: mensfeld.pl
e-mail: maciej@mensfeld.pl