33
Ruby The Fun Bits Matthew Bennett @undecisive [email protected]

Ruby The Fun Bits

  • Upload
    pandr

  • View
    284

  • Download
    1

Embed Size (px)

DESCRIPTION

An introduction to all the things that make Ruby a fun programming language to learn.

Citation preview

Page 1: Ruby The Fun Bits

Ruby

The Fun Bits

Matthew Bennett@undecisive

[email protected]

Page 2: Ruby The Fun Bits

And you are...

Audience Participation

Page 3: Ruby The Fun Bits

Ruby is...

Object OrientedDuck TypedOpen SourceInterpretedCross PlatformGarbage collectedSuccinctFlexibleExpressiveSemicolon-free (if you wish)

Docum

entedP

erformant

Expressive

Explorable

Sim

pleF

unS

ugaryIntuitiveE

xtensibleF

unctionalO

rthogonal

Soc

ial

Rea

dabl

eIn

tere

stin

gW

eb s

cale

Japa

neas

eyA

re y

ou a

ctua

lly

Rea

ding

this

Utte

r to

shU

nico

rns

Car

ing

Cod

e

Page 4: Ruby The Fun Bits

levitating Happycat

Page 5: Ruby The Fun Bits

Terminology

IRB Interactive Ruby

Gems Libraries / Packages

Page 6: Ruby The Fun Bits

Terminology

Duck typing

Object orientation

Translation:

Coding like a HUMAN

Page 7: Ruby The Fun Bits

CS101: Classes / Objects

Page 8: Ruby The Fun Bits

Classes != objects

class Cookie

def sugary_high

“Woot”end

end

kitten = Cookie.new

kitten.sugary_high #=> “Woot”

Page 9: Ruby The Fun Bits

But classes are objects

Cookie = Class.new do

def sugary_high

“Woot”end

end

kitten = Cookie.new

kitten.sugary_high #=> “Woot”

Page 10: Ruby The Fun Bits

Traditional stylee

if one == :boring_sod

“Old Skewl”

else

“Badass”

end

Page 11: Ruby The Fun Bits

What if...

Page 12: Ruby The Fun Bits

The good stuff

feel_the_awesome! if can_i_handle_it?

Ruled by convention(ignorable) Shiny inline if

No more is_x()

Page 13: Ruby The Fun Bits

Failing to not be un-negated

use_ruby unless self.mad?

(Note: If you ever show me code with unless...else, I will kill you.)

Page 14: Ruby The Fun Bits

True Object Orientation

0.9.round #=> 1

“Groinal attachment”.reverse #=> "tnemhcatta laniorG"

100.times do

puts “I am a fish”

end

(P.S: Sorry if you are missing Red Dwarf for this rubbish presentation)

Page 15: Ruby The Fun Bits

Rescue me!

def something.fail

raise “The kitten is falling out of the tree”

something_that_will_never_happen

end

something.fail rescue “My hero!”

Page 16: Ruby The Fun Bits

Gratuitous Cat

Page 17: Ruby The Fun Bits

Classics

class Kitten < Moggy

attr_accessor :cuteness_score

def initialize@cuteness_score = 100000000

end

end

kitty = Kitten.new

kitten.cuteness_score #=> 100000000

Page 18: Ruby The Fun Bits

Classics

class Kitten < Moggy

attr_accessor :cuteness_score

def initialize@cuteness_score = 99E99

end

end

kitty = Kitten.new

kitten.cuteness_score #=> 99E99

Page 19: Ruby The Fun Bits

Classics

class Kitten < Moggy

attr_accessor :cuteness_score

def initialize@cuteness_score = “WTF”

end

end

kitty = Kitten.new

kitten.cuteness_score #=> “WTF”

Page 20: Ruby The Fun Bits

Classics

class Kitten < Moggy

attr_accessor :cuteness_score

end

kitty = Kitten.new

kitty.cuteness_score = :cuter_than_10_kitties

kitten.cuteness_score=(:cuter_than_10_kitties)

Page 21: Ruby The Fun Bits

Classics

class Kitten < Moggy

def cuteness_score

@cuteness_score

end

def cuteness_score=(mein_score)

@cuteness_score = mein_score

end

end

attr_reader :cuteness_score

attr_

writer

:c

utenes

s_sc

ore

Page 22: Ruby The Fun Bits

I can comez wiv?

Page 23: Ruby The Fun Bits

Hate your fellow developer

class String

def to_s

reverseend

end

“Fishy”.to_s #=> “yhsiF”

Page 24: Ruby The Fun Bits

Spread the (un)love

module Evil

def to_s

super.reverse

end

end

class Object ; include Evil ; end

Page 25: Ruby The Fun Bits

More funky

[ Object, String, Fixnum, Array ].each do | klass |

EEK = klass # class reopened below must be a constants,

class EEK # but constants do not have to be constant.

def to_s

“I'm gonna eat you little fishy”end

end

end(irb):81: warning: already initialized constant EEK(irb):81: warning: already initialized constant EEK(irb):81: warning: already initialized constant EEK

Page 26: Ruby The Fun Bits

Because you are worth it

● You deserve:– A language that obeys your whims

– A language that allows you to do the logically impossible

– A language that tries desperately to be your friend

VOTE RUBY!

Page 27: Ruby The Fun Bits

Questions?

Page 28: Ruby The Fun Bits

Q&A

irb(main):003:0* puts "Hello Nrug"Hello Nrug=> nil

Show us some ruby in IRB!

More examples of class / object, and accessors

irb(main):004:0> class Questionirb(main):005:1> attr_accessor :titleirb(main):006:1> end=> nilirb(main):007:0> q = Question.new=> #<Question:0x007fd44a947160>irb(main):008:0> q.title=> nilirb(main):009:0> q.title = "Why won't my baby stop drinking rum?"=> "Why won't my baby stop drinking rum?"irb(main):010:0> q.title=> "Why won't my baby stop drinking rum?"irb(main):011:0> q.title=("Why won't my baby stop drinking rum?")=> "Why won't my baby stop drinking rum?"irb(main):012:0> q.title=("Why won't my baby stop drinking rum?").reverse=> "?mur gniknird pots ybab ym t'now yhW"irb(main):013:0> q.title=("Why won't my baby stop drinking rum?").split(' ').reverse.join(' ')=> "rum? drinking stop baby my won't Why"

Page 29: Ruby The Fun Bits

More Q&A

# This is the full syntaxirb(main):014:0> def funnyirb(main):015:1> beginirb(main):016:2* 10 / 0irb(main):017:2> rescue irb(main):018:2> "You FOOL!"irb(main):019:2> endirb(main):020:1> end=> nilirb(main):021:0> funny=> "You FOOL!"

# But if your methods are small enough, # begin...end can be implied irb(main):022:0> def funnyirb(main):023:1> 10 / 0irb(main):024:1> rescueirb(main):025:1> "You FOOL!"irb(main):026:1> end=> nilirb(main):027:0> funny=> "You FOOL!"

How would you do a traditional rescue?

Page 30: Ruby The Fun Bits

Extra Awesome Q&A

irb(main):044:0* a = "adsihudsbhjdsghjasjh"irb(main):051:0> def a.find_jirb(main):052:1> self.scan(/j/).countirb(main):053:1> end=> nilirb(main):054:0> a.find_j=> 3irb(main):055:0> a

# Here is a different String. It will not have the method.=> "adsihudsbhjdsghjasjh"irb(main):056:0> "ahgakwdhabhmsbd"=> "ahgakwdhabhmsbd"irb(main):057:0> "ahgakwdhabhmsbd".find_jNoMethodError: undefined method `find_j' for "ahgakwdhabhmsbd":String

from (irb):57from /Users/matthew/.rbenv/versions/1.9.3-p194/bin/irb:12:in

`<main>'

Here I try to show that you can add methods on objects, not just on classes

Page 31: Ruby The Fun Bits

Q&A For Fun And Profit

irb(main):028:0> def destroy_the_world_with_my_massive_laserirb(main):029:1> start_laserirb(main):030:1> destroy_worldirb(main):031:1> have_cocktailsirb(main):032:1> end

Question: I hear programmers complaining a lot about badly commented code, and keeping comments up to date. How does Ruby mitigate this?

Answer: The ruby community drives certain standards. One of these is a convention for very short methods and descriptive method names:

When code looks like this, the only reason to add comments is to document your gem for people who can't be bothered to look through the code.

Another question asked: What tools can you use in ruby to ensure conventions are followed?

Answer: I have a large bamboo stick that works really well. For a serious answer, there is ruby support in IDEs such as Netbeans and Eclipse, but these are rarely faultless. Peer pressure is by far the easiest and most reliable tool.

Page 32: Ruby The Fun Bits

Rocking that Q&A

irb(main):062:0* class Kittyirb(main):063:1> selfirb(main):064:1> end=> Kittyirb(main):065:0> class Kittyirb(main):066:1> "hi"irb(main):067:1> end=> "hi" # Question: When do I use @@varname – Answer: Never! # We can make use of “self” and the fact that you can create # methods on objects, and that classes are also objects...irb(main):068:0> class Kittyirb(main):069:1> def self.leg_countirb(main):070:2> 4irb(main):071:2> endirb(main):072:1> end=> nilirb(main):073:0> class Kittyirb(main):074:1> def self.leg_countirb(main):075:2> @leg_count # Class-level variables!irb(main):076:2> endirb(main):077:1> end=> nil # @@varname has some odd side effects. It is rarely needed.

Now I show that it's not just methods that return their final value – classes do too...

Page 33: Ruby The Fun Bits

And now for the finale

irb(main):090:0> class Kittyirb(main):091:1> class << self irb(main):092:2> attr_accessor :leg_countirb(main):093:2> endirb(main):094:1> end=> nilirb(main):095:0> Kitty.leg_count = 4000=> 4000

Finally, using a handy trick involving reopening classes, and the value of “self”, we can create getters and setters on the class level

Final notes:Unlike certain compiled languages, class definitions are essentially just code. They get evaluated line by line, so a “puts” statement in a class gets called as the class is being set up.

If anyone has any questions, or bits of code that they can't get to work for love nor money, by all means send me a gist. My twitter username is @undecisive.

Ruby is a wonderful language, and you have to try quite hard to find its limits. http://www.confreaks.com/ Have hundreds of awesome presentations on ruby for free. Check them out!