Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ruby Idioms

Ruby Idioms

Florian Plank

February 12, 2014
Tweet

More Decks by Florian Plank

Other Decks in Programming

Transcript

  1. - Soft tabs, two space indent - Lines shorter than

    80 characters - No spaces after [( and before )] - Methods: snake_case - Classes/Modules: CamelCase - Constants: SCREAMING_SNAKE_CASE - Space after commas: foo(a, b)
  2. if answer == 42 then # ... elsif foo ==

    'foo' then # ... else # ... end
  3. if answer == 42 then # ... elsif foo ==

    'foo' then # ... else # ... end
  4. def foo(name, options) # ... end foo('bar', {:something => 'else',

    :answer => 42}) foo('bar', :something => 'else', :answer => 42)
  5. Point = Struct.new(:x, :y) do def to_s "[#{x}, #{y}]" end

    end Point.new(0,0).to_s # => "[0, 0]"
  6. class Parent @@class_var = "parent" def self.print_class_var puts @@class_var end

    end class Child < Parent @@class_var = "child" end Parent.print_class_var # => "child"
  7. {:foo => "bar", :baz => 42}.each do |key, value| puts

    "#{key}: #{value}" end # foo: bar # baz: 42 # => {:foo=>"bar", :baz=>42}
  8. [[:foo, "bar"], [:baz, 42]].each do |(key, value)| puts "#{key}: #{value}"

    end # foo: bar # baz: 42 # => {:foo=>"bar", :baz=>42}
  9. [[:foo, "bar"], [:baz, 42]].each do |(_, value)| puts value end

    # bar # 42 # => [[:foo, "bar"], [:baz, 42]]