Ruby was initially designed to be a successor of the Perl programming language, which also means that it inherited a lot of Perl's expressiveness. To celebrate this, the TRIC¹ contest was invented: Write the most Transcendental, Imbroglio Ruby program! Illustrate some of the subtleties (and design issues) of Ruby! Show the robustness and portability of Ruby interpreters! Stabilize the spec…
Jan Lelis
https://idiosyncratic-ruby.com/ · 75 posts · history since 2015 · active
24 Aug 2020
17 Aug 2020
Have you ever been confused by the __underscores__ required by some of __RUBY__'s features? You can get it right with this overview of all of "super snake" keywords and methods. There are three different types of underscore-wrapped syntaxes in the Ruby core language: keywords Object methods and Kernel methods. Let us take a look at each of them, and understand…
14 Aug 2020
The Ruby core team cares a lot about Unicode, and this is why we have pretty good Unicode support in the language. Even though the Unicode standard evolves constantly - it gets updated at least once a year - Ruby's Unicode support is often only a little bit behind the current version of Unicode. The following tables list which Ruby…
12 Aug 2020
Recent Ruby versions allow you to choose from a wide-range of uppercase letters - beyond just ASCII - to start a constant / class name: class Österreich # 00D6 ├─ Ö ├─ LATIN CAPITAL LETTER O WITH DIAERESIS end # Syntax OK However, it is not possible to use just any Unicode character: class ℻ # 213B ├─ ℻ ├─…
11 Aug 2020
Ruby's mode of operation can be altered with some --enable-* / --disable-* command-line switches. By default, all of the following features are activated, except for the frozen strings and the JIT: Feature CLI Option to Change Description RubyGems --disable-gems RubyGems is the package manager of Ruby, which is required to load 3rd party Ruby libraries¹. RUBYOPT --disable-rubyopt The RUBYOPT ENV…
10 Aug 2020
What is your wild guess: How many different ways does Ruby provide for inserting a NULL byte into a double-quoted string? There are exactly 43 options¹! Here is the list, put together with some ideas from Episode 61: Meta Escape Control: Directly embedded NULL byte # => "\u0000" "\0" # => "\u0000" "\x00" # => "\u0000" "\x0" # => "\u0000"…
6 Aug 2020
How does nothing (as in nil, null, or nan) compare to nothing? Equality Equality == nil 0 0.0 0i 0r NaN¹ nil true false false false false false 0 false true true true true false 0.0 false true true true true false 0i false true true true true false 0r false true true true true false NaN false false false…
4 Aug 2020
The introduction of pattern matching in Ruby 2.7 brought us a new style of multi-assigning local variables: The pattern assignment, or, how you could also call it, the assignment in-style. After you have deactivated the warnings for experimental features, try the following piece of code: [1, 2, 3, 4] in [first, second, *other] Think: Put [1, 2, 3, 4] into…
3 Aug 2020
Ruby's Warning module learned some new tricks in Ruby 2.7: Support for muting different categories of compile warnings has been introduced. This is a mechanism on top of the warning level reflected by the $VERBOSE variable. You can now silence deprecation warnings: These are aspects of the language which will be removed or changed in a future version of Ruby.…
31 May 2018
Ruby comes with good support for Unicode-related features. Read on if you want to learn more about important Unicode fundamentals and how to use them in Ruby… …or just watch my talk from RubyConf 2017: ⑩ Unicode Characters You Should Know About as a 👩💻 Ruby ♡ Unicode Characters in Unicode Codepoints & Encodings Grapheme Clusters Normalization Confusables Case-Mapping Case-Folding…
15 May 2018
Starting with Ruby 2.5¹ it is possible to customize the behavior of Kernel#warn through the Warning module. Here is how: def Warning.warn(w) # super calls the original behavior, which is printing to $stderr super "\e[31;1mRUBY WARNING: \e[22m#{w.sub(/warning: /, '')}\e[0m" end # # # # examples warn "test" # => RUBY WARNING: test { a: 1, a: 2 } # =>…
7 May 2018
Regexes, the go-to-mechanism for string matching, must not only be written, but also need to be applied. This episode acts as a reference with some style advice for working with regular expressions in Ruby. If you are looking for resources on writing the actual regexes, take a look at the link collection at the bottom. What do you Want to…
2 May 2018
When you get farther upwards the steep hill that is Ruby mastery, you will come across some powerful, yet slightly evil methods: instance_eval and class_eval¹. They allow you to execute code and define methods tied to a specific class, at the same time giving you access to outer scope variables through the Ruby block syntax. Their exact behavior varies, depending…
31 May 2016
Ruby was created in 1993 and has come a long way. The preferred style of coding has changed quite a lot and solid best practice has emerged (though, as always, one size does not fit all). At the same time, Ruby's tool support could be better, the language is still too complex. Maybe, the time has come to remove some…
30 May 2016
Double-quoted strings can not only be used with interpolation, #{}, they also support various escape sequences, which are initiated with \. Escape sequences allow you to embed raw byte and codepoint values. Furthermore, there are shortcuts for common formatting and control characters. Byte Sequences There are two basic ways in which you can specify raw bytes to embed: \x00 (hexadecimal)…
29 May 2016
Ruby has more than one way to access additional information about the most recent regex match, like captured groups. One way is using the special variables $`, $&, $', $1 - $9, $+, and also in the MatchData object $~. They become available after using a method that matched a regex, or when the method supports a block, they are…
28 May 2016
Ruby's big DATA constant does more than you might expect! Everything after the __END__ keyword (at the beginning of the line) is not interpreted as Ruby, but can be retrieved with the big¹ DATA constant.² This is an example big-data.rb script: p DATA.read __END__ big data Big DATA is a File object, which you can read. The example will output…
27 May 2016
Ruby supports magic comments (interpreter instructions) at the top of the source file, mostly known for setting a source files' Encoding. This is the most common use case, but there is more you can do. Source File Encoding The default encoding of string literals in a Ruby file is UTF-8: p "".encoding # => #<Encoding:UTF-8> You can change it like…
26 May 2016
%a %A %b %B %c %C %d %D %e %F %g %G %h %H %I %j %k %l %L %m %M %n %N %p %P %Q %r %R %s %S %t %T %u %U %v %V %w %W %x %X %y %Y %z %Z %+ %% - _ 0 ^ # : Date and time formatting is traditionally done with…
25 May 2016
How come that Ruby has two ASCII encodings? Encoding.name_list.grep(/ASCII/) # => ["ASCII-8BIT", "US-ASCII"] Which one is the normal one you should use for ASCII? Aliases ASCII-8BIT US-ASCII BINARY ASCII ANSI_X3.4-1968 646 So, US-ASCII is aliased to ASCII, but then what is ASCII-8BIT for? Encodings' RDoc has some help: Encoding::ASCII_8BIT is a special encoding that is usually used for a byte…
24 May 2016
Another of Ruby's idiosyncrasies is equalness. It's not too complicated, but naming is an issue here. Four Concepts of Equalness equal? Object Identity Comparison This one is easy. Two objects should be considered identical. Think: x.object_id == y.object_id == Equality Equality This is the usual method to care about. Two objects should be treated the same. If the class supports…
23 May 2016
Similar to metaprogramming, Ruby's type conversion system has evolved over time. While the result functions, it is also a little inconsistent and suffers from poor naming. Let's put things in perspective: Implicit and Explicit Conversion Ruby objects are usually converted to other classes/types using to_* functions. For example, converting the String "42" to a Float is done with to_f: "42".to_f…
22 May 2016
Generated with Ruby 3.2.2, including RubyGems and DidYouMean: Object (Class) ├─ARGF (ARGF.class) ├─ARGV (Array) ├─ArgumentError (Class) ├─Array (Class) ├─BasicObject (Class) │ └─BasicObject → BasicObject ├─Binding (Class) ├─CROSS_COMPILING (NilClass) ├─Class (Class) ├─ClosedQueueError (Class) ├─Comparable (Module) ├─Complex (Class) │ └─I (Complex) ├─ConditionVariable (Class) ├─Data (Class) ├─DidYouMean (Module) │ ├─ClassNameChecker (Class) │ ├─Correctable (Module) │ ├─Formatter (Class) │ ├─Jaro
21 May 2016
It is less common, but similar to methods, constants have a visibility attached to them. You have the choice between private and public, and you can also mark a constant deprecated! Like with methods, the default visibility of a constant is public. Unlike methods, which have a lot of associated methods for metaprogramming, working with constants is easier: Module.methods.grep /const/…
20 May 2016
How many bytes (= ASCII characters) of Ruby code does it take to generate a SHA 256 hash sum of STDIN? 500 Bytes¹ q,z=[3,2].map{|t|i=l=1;(2..330).select{i-1<(l*=i)%i+=1}.map{|e|(e**t**-1*X=2**32).to_i&X-=1}} s=proc{|n,*m|a=0 m.map{|e|a^=n>>e|n<<32-e} a} i=$<.read.b<<128 (i+"\0"*(56.-(w=i.size)%64)+[~-w*8].pack('Q>')).gsub(/.{64}/m){w=$&.unpack'N*' y=z 64.times{|i|i>15&&w[i]=w[i-16]+(s[v=w[i-15],7,18]^v>>3)+w[i-7]+(s[w[i-2],17,19]^w[i-2]>>10)&X f=y[7]+s[u=y[4],6,11,25]+(u&y[5]^~u&y[6])+q[i]+w[i]
19 May 2016
Some words should not be chosen as identifiers for variables, parameters and methods in Ruby, because they clash with core methods or keywords. As long as you do not define a method with the name of a keyword, Ruby will not complain. Still, it is often better to avoid naming things like existing methods. It carries potential for future bugs…
18 May 2016
%a %A %b %B %c %d %e %E %f %g %G %i %o %p %s %u %x %X %% 0 $ # + - * space Ruby comes with a structured alternative to classic string interpolation: This episode will explore format strings, also known as the sprintf syntax. Recall the normal way of interpolating variables into a string: v =…
17 May 2016
Ruby was initially designed to be a successor of the Perl programming language, which also means that it inherited a lot of Perl's expressiveness. To celebrate this, the TRIC¹ contest was invented: Write the most Transcendental, Imbroglio Ruby program! Illustrate some of the subtleties (and design issues) of Ruby! Show the robustness and portability of Ruby interpreters! Stabilize the spec…
16 May 2016
Ruby was initially designed to be a successor of the Perl programming language, which also means that it inherited a lot of Perl's expressiveness. To celebrate this, the TRIC¹ contest was invented: Write the most Transcendental, Imbroglio Ruby program! Illustrate some of the subtleties (and design issues) of Ruby! Show the robustness and portability of Ruby interpreters! Stabilize the spec…
15 May 2016
There is nothing easier than parsing the command-line arguments given to your Ruby program: It is an array found in the special variable $*: $ ruby -e 'p $*' -- some command line --arguments ["some", "command", "line", "--arguments"] That is Too Easy! The trouble begins with supporting common arguments conventions, like GNU's, and combining it with Ruby DSLs. This has…
14 May 2016
Today, another snippet from the category don't try at home, might have unforeseeable consequences! Constant assignment¹ is not permanent in Ruby, so it is perfectly valid to do this: module A end class B def initialize p 42 end end A, B = B, A # warning: already initialized constant A # warning: previous definition of A was here #…
13 May 2016
In case you have wondered, what this top-level constant TOPLEVEL_BINDING is all about: It is, as its name suggest, the Binding of your script's main scope: a = 42 p binding.local_variable_defined?(:a) # => true p TOPLEVEL_BINDING.local_variable_defined?(:a) # => true def example_method p binding.local_variable_defined?(:a) # => false p TOPLEVEL_BINDING.local_variable_defined?(:a) # => true end example_method What is a practical use of it?…
12 May 2016
What happens when you invoke the Ruby interpreter, even before it executes your first line of code? Actually a lot! A few observations: Initial Load Path These are all locations you can Kernel#require from: $ ruby --disable-all -e 'puts $LOAD_PATH.map{ |path| "- #{path}" }' …/ruby-3.2.0/lib/ruby/site_ruby/3.2.0 …/ruby-3.2.0/lib/ruby/site_ruby/3.2.0/x86_64-linux …/ruby-3.2.0/lib/ruby/site_ruby …/ruby-3.2.0/lib/ruby/vendor_ruby/3.2.0 …/ruby-3.2.0/lib/ruby/vendor_ruby/3.2.0/x86_64-linux …/ruby-3.2.
11 May 2016
At some point when working with Ruby, you come across this mysterious RbConfig constant. A typical scenario is that you want to check which operating system your current program is executed on. You can do this with RbConfig::CONFIG['host_os'] or RbConfig::CONFIG['arch'], see the RubyGems source for an advanced example! The Ruby Configuration is a collection of low-level information about your operating…
10 May 2016
Ruby's Regexp engine has a powerful feature built in: It can match for Unicode character properties. But what exactly are properties you can match for? The Unicode consortium not only assigns all codepoints, it also publishes additional data about their assigned characters. When searching through a string, Ruby allows you to utilize some of this extra knowledge. Property Regexp Syntax…
9 May 2016
When exactly don't you have to :"escape" a Ruby symbol? Because this question is somehow related to the Ruby interpreter's internal usage of symbols, the rules are not the most obvious ones: : + Identifier¹, optionally appended by !, ?, or = (→ methods) :@ + Identifier¹ (→ instance variables) :@@ + Identifier¹ (→ class variables) :$ + Identifier¹ (→…
8 May 2016
A quick reminder that number literals in Ruby can be pretty fancy! Example Evaluates To Class Purpose 0x10 16 Integer Integers in hexadecimal (0-16) format 0o10¹ 8 Integer Integers in octal (0-8) format 0b10 2 Integer Integers in binary (0-1) format 1e1000 Float::INFINITY Float Floats in exponential notation 1i (0+1i)² Complex Shorthand for creating complex numbers 3/6r (1/2)² Rational Shorthand…
7 May 2016
In general, Ruby's reflection capabilities are pretty powerful, although not always logical. However, when reflecting on a method's (or proc's) usage, you are sometimes stuck with sad methods. Sad methods only work for code, that is written in Ruby itself. And Ruby itself (official MRI) is written in C, which limits such methods' usefulness quite a lot. This is an…
6 May 2016
Programming languages have been, and will always be categorized by their typing system. Naturally, large parts of the Ruby community (including myself) have some kind of aversion against static typing. But while Ruby goes down the route of being dynamically typed that does not mean that you are not allowed to use some form of types! 2020 update: Ruby 3.0…
5 May 2016
ERB stands for <%# Embedded Ruby %> and is the templating engine included in the Ruby Standard Library. While there are more recent gems that provide a better templating experience (see tilt for an abstraction, and erubis/erbse for an updated ERB), it is also convenient to have basic support directly in the standard library. However, it does not directly support…
4 May 2016
Is it a hash? Or is it a hash? hash = {"Idiosyncratic" => "Ruby"} hash["Idiosyncratic"] # => "Ruby" hash.compare_by_identity idiosyncratic_in_variable = "Idiosyncratic" hash[idiosyncratic_in_variable] # => nil hash["Idiosyncratic"] # => "Ruby" Hash#compare_by_identity changes the semantics of what is equal in a hash and what not. Only if exact the same object is passed in, the value will be retrieved. Please note:…
3 May 2016
RubyGems is bundled with core Ruby since 1.9, which was first released in 2007. As long as you do not run Ruby with the $ ruby --disable-gems flag, it is available to you without having to install anything. This also means that you can use some of RubyGems' support utilities for free! 1) Current Platform Info Gem::Platform.local.os # => "linux"…
2 May 2016
Ruby's syntax is so expressive — it utilizes every printable, non-alphanumeric ASCII character as much as it cans. Sometimes, this can be confusing for beginners. The next sections show 4+ different meanings of every portrayed single character (not counting different meaning as custom string delimiter or meaning within a regex): Question Mark (4 Syntactical Meanings) The question mark is a…
1 May 2016
If you don't like errors in your code, you will have to fix them. This handy list of Ruby's errors will hopefully help you do so! (And welcome back for the second season of Idiosyncratic Ruby!) Built-in Exceptions Exception Thrown by core Ruby when Remarks NoMemoryError The Ruby interpreter could not allocate the required memory "Idiosyncratic" * 100_000_000_000 ScriptError -…
31 May 2015
This is a summary of reasons why you should still use Ruby: It is a language with a terrific community (welcoming and always questioning itself) and ecosystem (a lot of problems already solved), which is beautiful (focus on productivity), a little conservative (in the sense that it is easy to work with), and general purpose (a good choice in most…
30 May 2015
Ruby's regex engine defines a lot of shortcut character classes. Besides the common meta characters (\w, etc.), there is also the POSIX style expressions and the unicode property syntax. This is an overview of all character classes: Meta Chars Char Negation ASCII Unicode . - ¹ Any ¹ Any \X - Any Grapheme clusters (\P{M}\p{M}*) \d \D [0-9] ² ASCII…
29 May 2015
If you take a closer look, you'll notice that Ruby's grammar has quite a few edge-case where its syntax is inconsistent or ambiguous: Binary Minus vs Minus taken as Unary Method Argument >> [1,3,4,5].size - 1 # => 3 >> [1,3,4,5].size -1 # wrong number of arguments(1 for 0) No Simple Rule, if a Symbol can be Displayed Without the…
28 May 2015
There is an operator in Ruby, that does nothing: The unary plus operator. It is part of the language for keeping symmetry with the unary minus operator! This is awesome, an operator for free! How can we utilize it? Update: In Ruby 2.3, the plus operator got its first purpose: Create an unfrozen copy of a string string = "frozen…
27 May 2015
Code Golf is the art of writing the shortest program possible. The less bytes the better. And the competition is just ridiculously strong! Head over to Anarchy Golf if you want to see more! A good beginner's problem is printing out Pascal's Triangle: Spend a few days to get to 45 bytes. Spend a few months to get to 43…
26 May 2015
Ruby has three default encodings. One of them is the default source encoding, which can be set using a magic comment in the file's first line, or in the second line if the first line is taken by a shebang. Default source encoding (UTF-8): p "".encoding #=> #<Encoding:UTF-8> With encoding comment (file_with_magic_comment.rb): # coding: cp1252 p "".encoding #=> #<Encoding:Windows-1252> See…
25 May 2015
Ruby clutters its objects a lot with methods for metaprogramming other methods: Class.instance_methods.grep /method/ => [:instance_methods, :public_instance_methods, :protected_instance_methods, :private_instance_methods, :method_defined?, :public_method_defined?, :private_method_defined?, :protected_method_defined?, :public_class_method, :private_class_method, :instance_method, :public_instance_method, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :method,
24 May 2015
If you change one line in Ruby's source, it will support goto statements! You can install a patched version via RVM's patch feature: $ rvm install 2.2.2 -n goto --patch http://git.io/vfxF2 $ rvm use 2.2.2-goto What to do to play around with this new feature? Let's reimplement this famous bug in Ruby: # prepare some dummy data hashCtx = hashOut…
23 May 2015
Tired of good old, but slow Ruby? Try one of Ruby's successors: Name Compiles To Description Crystal Machine Fast Ruby Mirah JVM Fast Ruby in Java Opal JS Ruby for JavaScript CoffeeScript JS JavaScript for Rubyists Elixir BEAM Ruby for Erlang Scala JVM Multi-Paradigm Ruby Rooby Machine Simple Ruby Rubex Machine Ruby Extensions Ruby Goby Machine Go meets Ruby All…
22 May 2015
Ruby has a built-in feature that is much like Literate CoffeeScript. In contrast to it, this Ruby option will not ignore literature, but garbage: -x[directory] Tells Ruby that the script is embedded in a message. Leading garbage will be discarded until the first line that starts with “#!” and contains the string, “ruby”. Any meaningful switches on that line will…
21 May 2015
Ruby's URI standard library contains a very sophisticated regex for matching URLs: "At https://idiosyncratic-ruby.com you can learn about the " \ "obscure parts of Ruby"[URI.regexp] # => "https://idiosyncratic-ruby.com" This regex is built in uri/rfc2396_parser.rb and looks like this: $ ruby -v ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux] $ ruby -r uri -e 'p URI.regexp' / ([a-zA-Z][\-+.a-zA-Z\d]*): (?# 1: scheme) (?:…
20 May 2015
A guide to Ruby's stdlib and available alternatives. Please note: The standard library was turned into gems, see stdgems.org for up-to-date information on all standard gems! Standard Library Overview Library Sources Description Alternatives abbrev mri Small library that finds the shortest abbreviation to identify one string amongst many - base64 mri Encodes and decodes strings to a Base64 representation. Implemented…
19 May 2015
This episode takes a look at the unusual use of symbols in one of Ruby's core APIs: Enumerable#chunk The chunk method splits the receiver object into multiple enumerators, using the rule defined in the block. It keeps together the parts that match in series. It then passes the result of this rule and an enumerator of the successive elements to…
18 May 2015
Ruby's Struct class is a convenient way to create Ruby classes, which already have some attributes defined. If you are not familiar with structs, you should watch Avdi Grimm's introduction to structs! But in many cases there is something better than structs: Gems that Define Attributes for "Plain Old Ruby Objects" Instead of using a specialized struct-class (which has different…
17 May 2015
One of Ruby's goals was to replace popular unix stream editors like awk or sed, which both have the concept of manipulating files in a line-based manner. Ruby has the -n option for this: Causes Ruby to assume the following loop around your script, which makes it iterate over file name arguments somewhat like sed -n or awk. while gets…
16 May 2015
Ruby allows you to change key functionality of the language. This means, it is also possible to break key functionality! Six examples of Ruby code you should never use: Undefining Core Methods The simplest way to change Ruby's global behavior is monkey patching: Nothing stops you from altering important core methods: class Module; undef append_features; end This line will break…
15 May 2015
All Ruby syntaxes¹ that represent the R string literal: (1) Double Quoted Literal "R" (1) Single Quoted Literal 'R' (1) Single Char Literals ?R (9) Heredocs <<"STRING" R STRING <<'STRING' R STRING <<STRING R STRING <<-"STRING" R STRING <<-'STRING' R STRING <<-STRING R STRING <<~"STRING" R STRING <<~'STRING' R STRING <<~STRING R STRING (66) Percent Syntax / Q %Q\0R\0 %Q\x01R\x01…
14 May 2015
There are two very different ways to create local variables in Ruby. You are probably familiar with the classical way: a, b = "$", "€" a # => "$" b # => "€" It is simple to understand and looks good. But Ruby would not be Ruby, if there weren't for more obscure ways to assign variables: You could rewrite…
13 May 2015
Ruby puts a lot of effort into its Enumerable module, offering a lot of different ways of iterating through collections. It is one of the reasons for Ruby's success, but you can also call it idiosyncratic, sometimes. This episode portraits enumerables' three handy slice_* methods. Slicing Enumerables Slicing lets you divide a collection into sub-collections. Take this array: a =…
12 May 2015
Some of IRB's command-line options can be called idiosyncratic as well. Take math mode¹ as an example: It will require the infamous mathn library on start up: $ irb -m >> Math #=> CMath >> 3/2 #=> (3/2) >> !!defined?(Vector) #=> true ¹ Math mode actually has been removed in Ruby version 2.5 And another one surprised me: You can…
11 May 2015
You are here for a collection of 10 advanced features of regular expressions in Ruby! Regex Conditionals Regular expressions can have embedded conditionals (if-then-else) with (?ref)then|else. "ref" stands for a group reference (number or name of a capture group): # will match everything if string contains "ä", or only match first two chars regex = /(.*ä)?(?(1).*|..)/ "Ruby"[regex] #=> "Ru" "Idiosyncrätic"[regex]…
10 May 2015
Ruby's ENV object gives you access to environment variables. It looks like normal Ruby hash: ENV["TERM"] #=> "xterm" ENV["SOMETHING"] = "NEW" #=> "NEW" But this is only the surface. Turns out ENV is a special object: ENV.class #=> Object It is hash-like, but lacks some functionality: ENV.flatten # NoMethodError ENV.default = "MyNullObject" # NoMethodError Besides this, it behaves like an…
9 May 2015
This is an overview of all the special, two-letter (and other) global variables in Ruby, which Ruby inherited from Perl. For the purpose of improving code readability, Ruby comes with English.rb in its standard library (or Deutsch.rb as gem), which provides non-cryptic aliases and some documentation. Ruby also defines some three-letter global variables that mirror CLI options ($-…) Types of…
8 May 2015
One of the never-ending style battles in Ruby land is module_function vs extend self. Both enable you to define module methods, which can be called not only from instance level, but also from class level. This enables you to make modules that can optionally be include'd into your current scope, which makes sense if the module contains non-state changing methods…
7 May 2015
There is a command-line switch to enable command-line switches: -s Enables some switch parsing for switches after script name but before any file name arguments (or before a --). Any switches found there are removed from ARGV and set the corresponding variable in the script. In this context "corresponding variable" means global variable. Let's see this in action (the -e…
6 May 2015
There is a one-liner on the internet that will start a local web server, for serving all the static files in your current directory: $ python -m SimpleHTTPServer 8080 Or with Python 3: $ python3 -m http.server Rubyists generally do not want to rely on Python, so there is a Ruby equivalent: $ ruby -run -e httpd . -p 8080…
5 May 2015
The script lines feature is probably the most famous example for idiosyncratic naming in Ruby! Ruby can save all source files you load or require as strings. This is useful for debugging utilities, for example, standard library's debug and tracer both use these capabilities. This is possible with the script lines object: It is a Ruby hash that stores all…
4 May 2015
a A b B c C d D e E F g G h H l L m m0 M n N p P q Q s S u U v V w x X Z @ ! * < > _ Ruby comes equipped with a powerful option for low level string manipulation: String#unpack and its counter part Array#pack.…
3 May 2015
Ruby has some ways to turn on debug mode, which library authors can use to print out extra information for interested users. But unfortunately, there are multiple debug modes in Ruby. When to use which one? Consider you have this code: def production_method puts "I am doing the right thing part 1" # @a is really intereting here puts "I…
2 May 2015
Ruby strings are powerful. You could say Ruby is built around manipulating strings. There are tons of ways how to work with strings and as of Ruby 2.7.1 String offers 130 instance methods. Knowing them well can save you a lot of time. What follows is a list of 10 lesser known things about strings: Some of them useful, some…
1 May 2015
Compared to other languages, Ruby does not have very good tool support for development. This might not be a problem for many of us: In the end, humans create the code, and not the tools. Nevertheless, it would be great to have better tools. Or at least valid syntax highlighting! The following table shows popular options for code highlighting, but…