The document introduces Ruby, describing its origins and key features. It discusses how Ruby was designed to be more powerful than Perl and more object-oriented than Python. It also emphasizes that Ruby aims to make programming enjoyable and help programmers be productive and happy. The document then demonstrates various Ruby concepts like classes, objects, and the interactive REPL interface.
7. Yukihiro “Matz” Matsumoto “ I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python. That's why I decided to design my own language.”
8. Yukihiro “Matz” Matsumoto “ I hope to see Ruby help every programmer in the world to be productive, to enjoy programming, and to be happy. “ That is the primary purpose of the Ruby language.”
9. Yukihiro “Matz” Matsumoto “ Often people, especially computer engineers, focus on the machines. They think, ‘By doing this, the machine will run faster. By doing this, the machine will run more effectively. By doing this, the machine will something something something.’ They are focusing on machines. But, in fact, we need to focus on humans.”
10. for ( var i = 0 ; i < 3 ; i ++ ) { alert ( 'Hello, world!' ); }
11. for ( var i = 0 ; i < 3 ; i ++ ) { alert ( 'Hello, world!' ); } 3 .times do puts 'Hello, world!' end
12. var people = [ 'Rob' , 'Eugene' , 'Crystal' ]; for ( var i = 0 ; i < people. length ; i ++ ) { alert (people[i] + ' loves Ruby' ); }
13. var people = [ 'Rob' , 'Eugene' , 'Crystal' ]; for ( var i = 0 ; i < people. length ; i ++ ) { alert (people[i] + ' loves Ruby' ); } [ 'Rob' , 'Eugene' , 'Crystal' ].each do | name | puts "#{name} loves Ruby" end
14. var today = new Date (); today. setDate (today. getDate () + 2 );
15. var today = new Date (); today. setDate (today. getDate () + 2 ); 2 .days.from_now
16. Yukihiro “Matz” Matsumoto “ Sometimes people jot down pseudo-code on paper. If that pseudo-code runs directly on their computers, it’s best, isn’t it? “ Ruby tries to be like that, like pseudo-code that runs.”
50. if person.has_red_hair? Sun .burn person end unless car.sugar_in_gas_tank? car.start end
51. if person.has_red_hair? Sun .burn person end unless car.sugar_in_gas_tank? car.start end 15 .times { wash_hands } if person.ocd?
52. if person.has_red_hair? Sun .burn person end unless car.sugar_in_gas_tank? car.start end 15 .times { wash_hands } if person.ocd? car.accelerate unless TrafficLight .is_red?
54. if just_worked_out and date_tonight take_a_shower end if love_mom or just_drunk get_a_tattoo end
55. if just_worked_out and date_tonight take_a_shower end if love_mom or just_drunk get_a_tattoo end if taco_bell? and not pepto_bismol_nearby? get_to_bathroom! end
85. Class, Object, Module and all other classes are instances of a class Class . Class, Module and Object have a circular dependency as they are in the core of the OO model
113. “ When I am working on a problem I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong.” — R. Buckminster Fuller
115. return gene_pool[rand(gene_pool.size)].send feature class Array def random return self [rand( self .length)] end end
116. return gene_pool[rand(gene_pool.size)].send feature class Array def random return self [rand( self .length)] end end return gene_pool.random.send feature
117. unless []. respond_to ? 'random' class Array def random return self [rand( self .length)] end end end
119. David Heinemeier Hansson (DHH) “ Why Ruby” http://confreaks.net/system/assets/datas/694/original/431-rubyconf2010-keynote-why-ruby-small.mp4?1291226733
120. “ UNIX was not designed to stop its users from doing stupid things, as that would also stop them from doing clever things.” — Doug Gwyn
121. “ There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code.” — Anonymous
122. class Array def random return self [rand( self .length)] end end class Person attr_accessor 'gender' , 'eyes' , 'chin' , 'name' def initialize ( gender,eyes,chin ) @gender = gender @eyes = eyes @chin = chin end def + ( other_person ) gene_pool = [ self ,other_person] Person . new selection(gene_pool, 'gender' ), selection(gene_pool, 'eyes' ), selection(gene_pool, 'chin' ) end def selection ( gene_pool,feature ) return gene_pool.random.send feature end private 'selection' end
123. using System;using System.Collections.Concurrent;using System.Collections.Specialized;using System.ComponentModel.Composition;using System.Diagnostics;using System.IO;using System.IO.Compression;using System.Net;using System.Text.RegularExpressions;using System.Threading;using System.Linq;using Newtonsoft.Json;using NLog;using Raven.Abstractions.Data;using Raven.Abstractions.Exceptions;using Raven.Abstractions.MEF;using Raven.Http.Abstractions;using Raven.Http.Exceptions;using Raven.Http.Extensions;using Formatting = Newtonsoft.Json.Formatting;namespace Raven.Http{ public abstract class HttpServer : IDisposable { private const int MaxConcurrentRequests = 192; protected readonly IResourceStore DefaultResourceStore; protected readonly IRavenHttpConfiguration DefaultConfiguration; private readonly ThreadLocal<string> currentTenantId = new ThreadLocal<string>(); private readonly ThreadLocal<IResourceStore> currentDatabase = new ThreadLocal<IResourceStore>(); private readonly ThreadLocal<IRavenHttpConfiguration> currentConfiguration = new ThreadLocal<IRavenHttpConfiguration>(); protected readonly ConcurrentDictionary<string, IResourceStore> ResourcesStoresCache = new ConcurrentDictionary<string, IResourceStore>(StringComparer.InvariantCultureIgnoreCase); private readonly ConcurrentDictionary<string, DateTime> databaseLastRecentlyUsed = new ConcurrentDictionary<string, DateTime>();
124. public int NumberOfRequests { get { return Thread.VolatileRead(ref physicalRequestsCount); } } [ImportMany] public OrderedPartCollection<AbstractRequestResponder> RequestResponders { get; set; } public IRavenHttpConfiguration Configuration { get { return DefaultConfiguration; } } public abstract Regex TenantsQuery { get; } private HttpListener listener; private static readonly Logger logger = LogManager.GetCurrentClassLogger(); private int reqNum; // concurrent requests // we set 1/4 aside for handling background tasks private readonly SemaphoreSlim concurretRequestSemaphore = new SemaphoreSlim(MaxConcurrentRequests); private Timer databasesCleanupTimer; private int physicalRequestsCount; public bool HasPendingRequests { get { return concurretRequestSemaphore.CurrentCount != MaxConcurrentRequests; } } protected HttpServer(IRavenHttpConfiguration configuration, IResourceStore resourceStore) {
129. protected virtual bool ShouldLogException(Exception exception) { return true; } private void FinalizeRequestProcessing(IHttpContext ctx, Stopwatch sw, bool ravenUiRequest) { LogHttpRequestStatsParams logHttpRequestStatsParam = null; try { logHttpRequestStatsParam = new LogHttpRequestStatsParams( sw, ctx.Request.Headers, ctx.Request.HttpMethod, ctx.Response.StatusCode, ctx.Request.Url.PathAndQuery); } catch (Exception e) { logger.WarnException("Could not gather information to log request stats", e); } ctx.FinalizeResonse(); sw.Stop(); if (ravenUiRequest || logHttpRequestStatsParam == null) return; LogHttpRequestStats(logHttpRequestStatsParam); ctx.OutputSavedLogItems(logger); } private void LogHttpRequestStats(LogHttpRequestStatsParams logHttpRequestStatsParams) { // we filter out requests for the UI because they fill the log with information // we probably don't care about them anyway. That said, we do output them if they take too // long.
130. if (logHttpRequestStatsParams.Headers["Raven-Timer-Request"] == "true" && logHttpRequestStatsParams.Stopwatch.ElapsedMilliseconds <= 25) return; var curReq = Interlocked.Increment(ref reqNum); logger.Debug("Request #{0,4:#,0}: {1,-7} - {2,5:#,0} ms - {5,-10} - {3} - {4}", curReq, logHttpRequestStatsParams.HttpMethod, logHttpRequestStatsParams.Stopwatch.ElapsedMilliseconds, logHttpRequestStatsParams.ResponseStatusCode, logHttpRequestStatsParams.RequestUri, currentTenantId.Value); } private void HandleException(IHttpContext ctx, Exception e) { try { if (e is BadRequestException) HandleBadRequest(ctx, (BadRequestException)e); else if (e is ConcurrencyException) HandleConcurrencyException(ctx, (ConcurrencyException)e); else if (TryHandleException(ctx, e)) return; else HandleGenericException(ctx, e); } catch (Exception) { logger.ErrorException("Failed to properly handle error, further error handling is ignored", e); } } protected abstract bool TryHandleException(IHttpContext ctx, Exception exception);
131. private static void HandleTooBusyError(IHttpContext ctx) { ctx.Response.StatusCode = 503; ctx.Response.StatusDescription = "Service Unavailable"; SerializeError(ctx, new { Url = ctx.Request.RawUrl, Error = "The server is too busy, could not acquire transactional access" }); } private static void HandleGenericException(IHttpContext ctx, Exception e) { ctx.Response.StatusCode = 500; ctx.Response.StatusDescription = "Internal Server Error"; SerializeError(ctx, new { Url = ctx.Request.RawUrl, Error = e.ToString() }); } private static void HandleBadRequest(IHttpContext ctx, BadRequestException e) { ctx.SetStatusToBadRequest(); SerializeError(ctx, new { Url = ctx.Request.RawUrl, e.Message, Error = e.Message }); }
137. webserver = TCPServer . new ( '127.0.0.1' , 3000 ) while (session = webserver.accept) session.print "HTTP/1.1 200/OK Content-type:text/html " request = session.gets filename = request.match( / (.*?) / )[ 1 ] filename = 'index.html' if filename == '' begin session.print File .read(filename) rescue Errno :: ENOENT session.print 'File not found' end session.close end
138. “ There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies.” — C.A.R. Hoare
139. class Person def + ( other_person ) gene_pool = [ self ,other_person] Person . new selection(gene_pool, 'gender' ), selection(gene_pool, 'eyes' ), selection(gene_pool, 'chin' ) end def selection ( gene_pool,feature ) return gene_pool[rand(gene_pool.size)].send feature end private 'selection' end
140. class Person def + ( other_person ) gene_pool = [ self ,other_person] Person . new selection(gene_pool, 'gender' ), selection(gene_pool, 'eyes' ), selection(gene_pool, 'chin' ) end def selection ( gene_pool,feature ) return gene_pool[rand(gene_pool.size)].send feature end private 'selection' end
141. class Person def + ( other_person ) gene_pool = [ self ,other_person] Person . new selection(gene_pool, 'gender' ), selection(gene_pool, 'eyes' ), selection(gene_pool, 'chin' ) end def selection ( gene_pool,feature ) return gene_pool[rand(gene_pool.size)].send feature end private 'selection' end
142. Implicit return Any statement in Ruby returns the value of the last evaluated expression
183. require 'json' require 'httparty' HTTParty.get(url) JSON.parse(text) user_input = gets print 'text' puts 'text' user_input.chomp my_array.each_with_index do |item,i| puts “#{item} is as position #{i}” end http://api.amp.active.com/search? v=json& k=keywords& m=meta:channel%3DRunning& api_key= wuhmn9ye94xn3xnteudxsavw exit 0
184. “ I am rarely happier than when spending an entire day programming my computer to perform automatically a task that would otherwise take me a good ten seconds to do by hand.” — Douglas Adams