SlideShare a Scribd company logo
Keith Bennett : What I Love About Ruby

This page last changed on Sep 17, 2008 by kbennett.


What I Love About Ruby
Keith Bennett

kbennett .at. bbsinc .dot. biz




Simplicity of Creating Instance Variables with Accessors and Mutators in Ruby

class Y
  attr_accessor :a
end


...creates an instance variable a, and an accessor and mutator.


Concise Idiom for Conditional (and Lazy) Initialization

@var ||= some_expensive_initialization


...means if var is undefined, define it, and if nil, do the initialization.


Numeric Constants Thousands Separators Supported

irb(main):002:0> 1_000_000
=> 1000000
irb(main):003:0> 1_000_000.class
=> Fixnum


Actually, all underscores are stripped, even if they do not separate thousands.


Shell Integration

A shell command enclosed in backticks will be run, and the value returned by the backticked command
will be the text the command sent to stdout:

irb(main):008:0>         `mkdir a b c d`
=> ""
irb(main):009:0>         `touch b/foo d/foo`
=> ""
irb(main):010:0>         emptydirs = `find . -type d -empty`
=> "./an./cn"
irb(main):011:0>         puts emptydirs
./a
./c
=> nil



Logical Syntax:

1.upto(10) { |i| puts i }

(100..200).each { |n| puts n }




Document generated by Confluence on Sep 18, 2008 09:45                                          Page 1
vs., in Java, for the first example:

for (int i = 0; i <= 10; i++) {
  System.out.println(i) ;
}



Ability to Specify Arrays (and Hashes) as Literals

and the Ease of Iterating Over Them

irb(main):018:0> ['collie', 'labrador', 'husky'].each { |breed|
  puts "Hi, I'm a #{breed}, and I know how to bark."
}
Hi, I'm a collie, and I know how to bark.
Hi, I'm a labrador, and I know how to bark.
Hi, I'm a husky, and I know how to bark.
=> ["collie", "labrador", "husky"]


Also:

%w(collie labrador husky)


can be used to create the array instead of:

['collie', 'labrador', 'husky']


A Hash:



irb(main):063:0> favorites = { :fruit => :durian, :vegetable => :broccoli }
=> {:fruit=>:durian, :vegetable=>:broccoli}



Ranges

water_liquid_range = 32.guatda.com/cmx.p0...212.0
=> 32.guatda.com/cmx.p0...212.0
irb(main):010:0> water_liquid_range.include? 40
=> true
irb(main):011:0> water_liquid_range.include? -40
=> false


Note: Ranges are not arrays; any number n, not just integers, such that 32.0 <= n < 212.0, is included
in the range.


Converting Ranges to Arrays:



irb(main):043:0> ('m'..'q').to_a
=> ["m", "n", "o", "p", "q"]



Blocks Used to Automatically Close Resources

File.open 'x.txt', 'w' do |file|
  file << 'Hello, world'




Document generated by Confluence on Sep 18, 2008 09:45                                            Page 2
end


The file is automatically closed after the block completes. If no block is provided, then the open function
returns the file instance:

irb(main):001:0>   f = File.open 'x.txt', 'w'
=> #<File:x.txt>
irb(main):002:0>   f << "Pleaaase, delete me, let me go..."
=> #<File:x.txt>
irb(main):003:0>   f.close
=> nil
irb(main):004:0>   puts IO.read('x.txt')
Pleaaase, delete   me, let me go...
=> nil



Simple File Operations

file_as_lines_array = IO.readlines 'x.txt'
file_as_single_string = IO.read 'x.txt'



Clean and Simple Syntax

puts Array.instance_methods.sort



Regular Expressions

irb(main):027:0>   'ruby' =~ /ruby/
=> 0
irb(main):028:0>   'rubx' =~ /ruby/
=> nil
irb(main):029:0>   'ruby' =~ /Ruby/
=> nil
irb(main):030:0>   'ruby' =~ /Ruby/i
=> 0



Arrays:

irb(main):001:0> nums = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
irb(main):006:0> nums.include? 3
=> true
irb(main):004:0> nums.collect { |n| n * n }
=> [1, 4, 9, 16, 25]
irb(main):002:0> nums.reject { |n| n % 2 == 0}
=> [1, 3, 5]
irb(main):003:0> nums.inject { |sum,n| sum += n }
=> 15
irb(main):052:0* distances_in_miles = [10, 50]=> [10, 50]
irb(main):053:0> distances_in_km = distances_in_miles.map { |n| n * 9.0 / 5.0 }
=> [18.0, 90.0]irb(main):016:0* twos = (0..10).map { |n| n * 2 }
=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
irb(main):017:0> fours = (0..5).map { |n| n * 4 }
=> [0, 4, 8, 12, 16, 20]
irb(main):018:0> twos - fours
=> [2, 6, 10, 14, 18]
irb(main):019:0> twos & fours


Document generated by Confluence on Sep 18, 2008 09:45                                                Page 3
=> [0, 4, 8, 12, 16, 20]
irb(main):020:0> fours * 2
=> [0, 4, 8, 12, 16, 20, 0, 4, 8, 12, 16, 20]
irb(main):021:0> twos + fours
=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 0, 4, 8, 12, 16, 20]



Built-in String Operations

   •   Case Conversions, Capitalization
   •   Left, Right, Sub
   •   Strip, Justify, Center
   •   Search and Replace (gsub)
   •   Insert, Delete




Document generated by Confluence on Sep 18, 2008 09:45            Page 4

More Related Content

PPTX
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
PDF
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
PDF
Simulator customizing & testing for Xcode 9
PDF
스위프트를 여행하는 히치하이커를 위한 스타일 안내
PDF
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
PDF
Building fast interpreters in Rust
PDF
Magicke metody v Pythonu
KEY
Invertible-syntax 入門
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
Simulator customizing & testing for Xcode 9
스위프트를 여행하는 히치하이커를 위한 스타일 안내
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
Building fast interpreters in Rust
Magicke metody v Pythonu
Invertible-syntax 入門

What's hot (13)

PDF
mongodb-introduction
PDF
はじめてのMongoDB
PDF
20110514 mongo dbチューニング
KEY
Scala Days 2011 - Rogue: A Type-Safe DSL for MongoDB
PPTX
20171014 tips for manipulating filesystem in julia
PDF
Cukeup nyc ian dees on elixir, erlang, and cucumberl
PDF
[131]해커의 관점에서 바라보기
PDF
HadoopとMongoDBを活用したソーシャルアプリのログ解析
PDF
Undrop for InnoDB
PDF
Solr @ Etsy - Apache Lucene Eurocon
KEY
Introducing CakeEntity
PDF
Future of HTTP in CakePHP
PPTX
High performance GPU computing with Ruby RubyConf 2017
mongodb-introduction
はじめてのMongoDB
20110514 mongo dbチューニング
Scala Days 2011 - Rogue: A Type-Safe DSL for MongoDB
20171014 tips for manipulating filesystem in julia
Cukeup nyc ian dees on elixir, erlang, and cucumberl
[131]해커의 관점에서 바라보기
HadoopとMongoDBを活用したソーシャルアプリのログ解析
Undrop for InnoDB
Solr @ Etsy - Apache Lucene Eurocon
Introducing CakeEntity
Future of HTTP in CakePHP
High performance GPU computing with Ruby RubyConf 2017
Ad

Viewers also liked (11)

PPTX
Right Compensation Plan
PDF
اليوم السعيد
PDF
a course
PDF
ruby
PDF
Eco musculoesqueletica (1)
PPT
E Learning Design
PPSX
How to Spend an Ideal Day on $10
PDF
I Love Ruby
PPT
كيف تخطط لمستقبلك
PDF
ruby
PPT
Right Compensation Plan
اليوم السعيد
a course
ruby
Eco musculoesqueletica (1)
E Learning Design
How to Spend an Ideal Day on $10
I Love Ruby
كيف تخطط لمستقبلك
ruby
Ad

Similar to ruby (20)

PPTX
Why everyone like ruby
ODP
What I Love About Ruby
PDF
Kickin' Ass with Cache-Fu (without notes)
 
PDF
Variables, expressions, standard types
PPTX
Why learn Internals?
PDF
A Few of My Favorite (Python) Things
PDF
All about Erubis (English)
PDF
Ruby Language - A quick tour
PDF
[E-Dev-Day 2014][4/16] Review of Eolian, Eo, Bindings, Interfaces and What's ...
PDF
JRuby 9000 - Optimizing Above the JVM
PDF
Hidden Gems in Swift
PDF
Memcached Presentation @757rb
PDF
Introduction to Python
PDF
Introduction to Ruby
KEY
Minicurso Ruby e Rails
KEY
Spl Not A Bridge Too Far phpNW09
PDF
DataMapper
PPTX
Code for Startup MVP (Ruby on Rails) Session 2
PPTX
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
PDF
Ruby and Rails by Example (GeekCamp edition)
Why everyone like ruby
What I Love About Ruby
Kickin' Ass with Cache-Fu (without notes)
 
Variables, expressions, standard types
Why learn Internals?
A Few of My Favorite (Python) Things
All about Erubis (English)
Ruby Language - A quick tour
[E-Dev-Day 2014][4/16] Review of Eolian, Eo, Bindings, Interfaces and What's ...
JRuby 9000 - Optimizing Above the JVM
Hidden Gems in Swift
Memcached Presentation @757rb
Introduction to Python
Introduction to Ruby
Minicurso Ruby e Rails
Spl Not A Bridge Too Far phpNW09
DataMapper
Code for Startup MVP (Ruby on Rails) Session 2
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Ruby and Rails by Example (GeekCamp edition)

More from mahersaif (7)

PPTX
مهارات قيادة فرق العمل
PPT
What is the Pre-Approved Program?
PPT
The Professional in Human Resources (PHR®) certification is designed for the ...
PPT
الخرائط الذهنية
PDF
دورتنا
PDF
ruby
PDF
I Love Ruby
مهارات قيادة فرق العمل
What is the Pre-Approved Program?
The Professional in Human Resources (PHR®) certification is designed for the ...
الخرائط الذهنية
دورتنا
ruby
I Love Ruby

ruby

  • 1. Keith Bennett : What I Love About Ruby This page last changed on Sep 17, 2008 by kbennett. What I Love About Ruby Keith Bennett kbennett .at. bbsinc .dot. biz Simplicity of Creating Instance Variables with Accessors and Mutators in Ruby class Y attr_accessor :a end ...creates an instance variable a, and an accessor and mutator. Concise Idiom for Conditional (and Lazy) Initialization @var ||= some_expensive_initialization ...means if var is undefined, define it, and if nil, do the initialization. Numeric Constants Thousands Separators Supported irb(main):002:0> 1_000_000 => 1000000 irb(main):003:0> 1_000_000.class => Fixnum Actually, all underscores are stripped, even if they do not separate thousands. Shell Integration A shell command enclosed in backticks will be run, and the value returned by the backticked command will be the text the command sent to stdout: irb(main):008:0> `mkdir a b c d` => "" irb(main):009:0> `touch b/foo d/foo` => "" irb(main):010:0> emptydirs = `find . -type d -empty` => "./an./cn" irb(main):011:0> puts emptydirs ./a ./c => nil Logical Syntax: 1.upto(10) { |i| puts i } (100..200).each { |n| puts n } Document generated by Confluence on Sep 18, 2008 09:45 Page 1
  • 2. vs., in Java, for the first example: for (int i = 0; i <= 10; i++) { System.out.println(i) ; } Ability to Specify Arrays (and Hashes) as Literals and the Ease of Iterating Over Them irb(main):018:0> ['collie', 'labrador', 'husky'].each { |breed| puts "Hi, I'm a #{breed}, and I know how to bark." } Hi, I'm a collie, and I know how to bark. Hi, I'm a labrador, and I know how to bark. Hi, I'm a husky, and I know how to bark. => ["collie", "labrador", "husky"] Also: %w(collie labrador husky) can be used to create the array instead of: ['collie', 'labrador', 'husky'] A Hash: irb(main):063:0> favorites = { :fruit => :durian, :vegetable => :broccoli } => {:fruit=>:durian, :vegetable=>:broccoli} Ranges water_liquid_range = 32.guatda.com/cmx.p0...212.0 => 32.guatda.com/cmx.p0...212.0 irb(main):010:0> water_liquid_range.include? 40 => true irb(main):011:0> water_liquid_range.include? -40 => false Note: Ranges are not arrays; any number n, not just integers, such that 32.0 <= n < 212.0, is included in the range. Converting Ranges to Arrays: irb(main):043:0> ('m'..'q').to_a => ["m", "n", "o", "p", "q"] Blocks Used to Automatically Close Resources File.open 'x.txt', 'w' do |file| file << 'Hello, world' Document generated by Confluence on Sep 18, 2008 09:45 Page 2
  • 3. end The file is automatically closed after the block completes. If no block is provided, then the open function returns the file instance: irb(main):001:0> f = File.open 'x.txt', 'w' => #<File:x.txt> irb(main):002:0> f << "Pleaaase, delete me, let me go..." => #<File:x.txt> irb(main):003:0> f.close => nil irb(main):004:0> puts IO.read('x.txt') Pleaaase, delete me, let me go... => nil Simple File Operations file_as_lines_array = IO.readlines 'x.txt' file_as_single_string = IO.read 'x.txt' Clean and Simple Syntax puts Array.instance_methods.sort Regular Expressions irb(main):027:0> 'ruby' =~ /ruby/ => 0 irb(main):028:0> 'rubx' =~ /ruby/ => nil irb(main):029:0> 'ruby' =~ /Ruby/ => nil irb(main):030:0> 'ruby' =~ /Ruby/i => 0 Arrays: irb(main):001:0> nums = [1,2,3,4,5] => [1, 2, 3, 4, 5] irb(main):006:0> nums.include? 3 => true irb(main):004:0> nums.collect { |n| n * n } => [1, 4, 9, 16, 25] irb(main):002:0> nums.reject { |n| n % 2 == 0} => [1, 3, 5] irb(main):003:0> nums.inject { |sum,n| sum += n } => 15 irb(main):052:0* distances_in_miles = [10, 50]=> [10, 50] irb(main):053:0> distances_in_km = distances_in_miles.map { |n| n * 9.0 / 5.0 } => [18.0, 90.0]irb(main):016:0* twos = (0..10).map { |n| n * 2 } => [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] irb(main):017:0> fours = (0..5).map { |n| n * 4 } => [0, 4, 8, 12, 16, 20] irb(main):018:0> twos - fours => [2, 6, 10, 14, 18] irb(main):019:0> twos & fours Document generated by Confluence on Sep 18, 2008 09:45 Page 3
  • 4. => [0, 4, 8, 12, 16, 20] irb(main):020:0> fours * 2 => [0, 4, 8, 12, 16, 20, 0, 4, 8, 12, 16, 20] irb(main):021:0> twos + fours => [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 0, 4, 8, 12, 16, 20] Built-in String Operations • Case Conversions, Capitalization • Left, Right, Sub • Strip, Justify, Center • Search and Replace (gsub) • Insert, Delete Document generated by Confluence on Sep 18, 2008 09:45 Page 4