Skip to content

Instantly share code, notes, and snippets.

@y8

y8/ruby.md Secret

Last active Apr 12, 2018
Embed
What would you like to do?

Day one, part II

Ruby in 60 seconds

  • Everything is an Object
  • Variables can refer to Objects
  • Objects can receive Method calls
  • Methods can change variables and send Method calls

(everything else is a KEYWORD of OPERATOR or LITERAL)

NOW YOU KNOW EVERYTHING THANK YOU

Expression

(...)\n

(...); (...)

(...) \
    (...)

Method call

    method
    method()

    receiver.method
    receiver.method()

    receiver   .   method

    receiver.method = ...
    receiver.method=...
    receiver.method=(...)

    1 + 1
    1.+(1)

		(Add: Prefix methods)

    -- -1
    + + + 1
    ! ! ! 1

    !-+-+-1

Variables

Local variables

starts with:

_ or lowercase [:alpha:]

then can be

_ or [:alpha:] or 0-9

default: raise NameError

Instance variables

@Same_as_local

(@ is sigil, /ˈsɪdʒəl/)

default: nil

Guess: method@wtf

Class variables

@@Same_as_local

default: nil

Global variables

$Same_as_local

ALOT of built-in perl-style shit (see globals.rdoc)

default: nil

Constants

	FromCapitalLetter

default: raise NameError

Keywords

38 of them

Control expressions

Операторные скобки — keyword ... end

if (expr1 == true) [then]
elsif (expr2 == true) [then]
else
end

unless (expr1 == false) [then]
else
end

Example: if not (name == "Alex")_ unless name == "Alex"_

(code) if (expr == true)
(code) unless (expr == false)

(expr) ? (expr == true) : (expr == false)

if ... then ... else ... end
unless ... then ... else ... end

case ...
when 1
when 2, 3
when 4 then
else
end

Note that case uses method ===

# Surprised?
... or ...
... and ...

Example: sms or tweet or mail or call wakeup and put_clothes and go_work

Loop keywords

while (... == true)
end

until (... == false)
end

... while ...
... until ...

begin
end while ...

[CENSORED]

for (variable) in (enumerable)
end

for ... in ... do
end

Definitions

module <ConstantName>
end

class <ConstantName> [< ParentName]
end

ParentName can be any Class object

class << <object>
end

def <method_name>
    yield [<arguments>]
    return [<arguments>]
	    super [<arguments>]
end

Method Naming

def <method_name> <argument_list>
    ...
rescue <Constant> [,<Constant>] [=> <local_variable>]
    ...
ensure
    ...
end

undef <method_name>

Logical Blocks

begin
    raise ...
rescue ...
    retry
else
ensure
end

Real blocks

... do [|<signature>|]
    next ...
    break ...
    redo
end

... {|<signature| ... }

"Method-like"

defined? (...)
alias <new> <old>

# Not possible in do ... end form
BEGIN { ... }
END { ... }

"Pointers"

__ENCODING__
__FILE__
__LINE__
__END__

"Literals"

self

nil
true
false

nil and false are only thing that is Truly False

Operators

Binary

&&      and
||      or

Unary

*obj    splat operator (day X)
&obj    almost to_proc alias

# Calling ! method on ...
not ...

WTF

->      lambda
?<x>    control sequence
::      Scope resolution operator

Rest of Ruby expressions are not operators, but method calls.

Assignment

Not Assignments (but assignment method calls)

<object>.method = (expression)

Assignment

<variable> = (expression)

Assignments with benefits (aka Abbreviated or Self)

<variable> *= (expression)

<variable> = <variable> * (expression)

Works for:

+ - * / % ** & | ^ << >>

Conditional assignments

When variable is false

<variable> ||= (expression)
<variable> || <variable> = (expression)

When variable is NOT false

<variable> &&= (expression)
<variable> && <variable> = (expression)

Multi-assignment and decomposition

a = 1, 2, 3       # [1, 2, 3]

a, b = b, a

a, b = 1          # 1     nil
a, b = 1, 2       # 1     2
a, b = 1, 2, 3    # 1     2

a, *b = 1, 2, 3   # 1     [2, 3]
*a, b = 1, 2, 3   # [1, 2]    3

a, *b, c = 1, 2, 3, 4  # 1, [2, 3], 4

a, (b, c) = [1, [2, 3, 4]]
a, (b, *c), *d = 1, [2, 3, 4], 5, 6

Same rules apply for method signatures!

Everything else

0. Comments

# Nothing to see here

=begin
  This is RDoc
  Perl-style multiline built-in docs
=end

1. Numeric

1000                        # Fixnum
1_000

0d1000
0b0111_1101_00_0
	0o1750
01750
0x3E8

1.0                         # Float
1000e-3
0.001e3

All of them immutable. But...

123_456_789_123_456_789     # BigNum

Is mutable, so it's not a literal. New object created each time.

2. String

String.new "New String"

'One'                       # One
"On #{1 + 1}"               # 'On' + (1 + 1).to_s

"No more \#{love}"          # No more #{love}

"There is\nEscape"          # There is
                            # Escape

'There no \nEscape'         # There no \nEscape

"It is #@funny in Philly"   # 'It is' + @funny.to_s + 'in Philly'
"I'm #@@classy."            # 'I\'m' + @@classy.to_s + '.'

Explain %? operator

%q< Any non-alpha as delimiter >
%q!
      Also    It            # Comments
      is      a             # are
        Multiline           # useles in this case
  !

%Q/ What is the #{love} /

<<HEREDOC
    This is here-doc with some #{love}.
HEREDOC

<<-FIN

  Now you can end lines more dramatically.

          FIN

<<-'FOR LIKE EVER'

  And there no more #{love}

      FOR LIKE EVER

<<-SUDDEN_METHOD.split      # You can call methods like this
    One was a race horse.
SUDDEN_METHOD

And not literally a literal. Returns new object each time.

3. Symbol (aka singleton string)

:symbol
:'string-like symbol without #{love}'
:"string-like symbol with #{love}"

%s* Have you got any #{love}? *
%S[ I bet you do! ]

Bonus: Never GC'ed

4. Arrays

Array.new
	[]

1, 2, 3

[1 + 1, 'Two', :three]          # [2, 'Two', :three]

%w{ 1 Two :three }              # ["1", "Two", ":three"]

%W/ #{1} #{'Two'} #{:three} /   # ["1", "Two", "three"]

%w[one two\ 3]                  # ["one", "two 3"]

%i{ Array of sybmols }          # [:Array, :of, :symbols]
%I{ Array of #{true} }          # [:Array, :of, :true]

# Btw, some fun with heredoc

[<<ONE, <<-TWO, <<THREE]
      This
ONE
      is
TWO
      it.
THREE

Not literal as well. New object each time.

5. Hash

Hash.new(default = nil)

{
  symbol: "value",
  "anything" => :anything,
  ["Wow"] => 0535,
}

Guess what? :)

6. Range

'a'..'z'      # a, b, c ... x, y, z
'a'...'z'     # a, b, c ... x, y

I hope you can guess.

7. Regular expression

/What is #{love}/

%r? yes ?  

Note: Interpolated

But there no %R :(

8. Shell command

`rm -rf /`

%x{ #{:whomai} }

Note: Interpolated

# Also, no %X. :|

Further reading:

Very important precedence is!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.