What I Love About Ruby
What I Love About Ruby
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> => "" irb(main):009:0> => "" irb(main):010:0> => "./a\n./c\n" irb(main):011:0> ./a ./c => nil `mkdir a b c d` `touch b/foo d/foo` emptydirs = `find . -type d -empty` puts emptydirs
Logical Syntax:
1.upto(10) { |i| puts i } (100..200).each { |n| puts n }
Page 1
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)
irb(main):063:0> favorites = { :fruit => :durian, :vegetable => :broccoli } => {:fruit=>:durian, :vegetable=>:broccoli}
Ranges
water_liquid_range = 32.0...212.0 => 32.0...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.
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> => #<File:x.txt> irb(main):002:0> => #<File:x.txt> irb(main):003:0> => nil irb(main):004:0> Pleaaase, delete => nil f = File.open 'x.txt', 'w' f << "Pleaaase, delete me, let me go..." f.close puts IO.read('x.txt') me, let me go...
Regular Expressions
irb(main):027:0> => 0 irb(main):028:0> => nil irb(main):029:0> => nil irb(main):030:0> => 0 'ruby' =~ /ruby/ 'rubx' =~ /ruby/ 'ruby' =~ /Ruby/ 'ruby' =~ /Ruby/i
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
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
Page 4