Ruby notes

From Helpful
Jump to navigation Jump to search
This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.




Semi-sorted

RubyGems, gems

RubyGems is a format for distributing ruby modules, a package manager, and the basis of collaborative indexes of ruby modules that are fairly easy to install as a gem.

RubyGems itself is a program that has to be installed relatively manually.

http://en.wikipedia.org/wiki/Ruby_gems


ERB / eRuby

...is a way of mixing HTML and ruby code (a la PHP, ASP, etc). Basically a very simple DSL/parser.


Basic ruby code; output, if any, is placed in the HTML:

 <% if foo %>
  ...
 <% end %>

Put result of expression into HTML (basically a shorthand of puts expression):

 <%= expression %>

Commented block (handy for debugging):

 <%# comment -- ignored -- useful in testing %>

further notes:

  • A line that starts with % is seen as <% line %>
  • a literal % is expressed as %%


In Rails(verify):

<%=h expression_that_needs_html_escaping %>


ERB has an implementation in the standard library(verify), and there are some re-implementations, such as erubis, which is faster and has some additional features.

See also:


Data types and syntax

📃 These are primarily notes, intended to be a collection of useful fragments, that will probably never be complete in any sense.



Numbers

Strings (mutable and immutable)

In-code string declarations can be single-quoted and double-quoted, which are different.

t = 'foo'    #raw string, no interpolation, no interpretation of escapes
u = 3
"Strings with interpolation: #{t} \n #{u}" 

Adjacent strings are concatenated

'foo' "bar" == "foobar"


Mutable strings (mutable objects in general) are the default, where the mutability refers to the fact that string objects can have their value changes.


Immutable objects come from mutable objectswhere (.freeze) has been called, either by you, or sometimes by some underlying code.

Immutable objects means that their value cannot change. This has its uses in certain optimizations, and it makes paralellism easier (since code can assume certain things, and this more or less forces you to code in a better style for parallelism), and is sometimes required of strings to be used in certain contexts.


Symbols

This article/section is a stub — some half-sorted notes, not necessarily checked, not necessarily correct. Feel free to ignore, or tell me about it.

Ruby's symbol objects are, perhaps, most generally, (code-level) identifiers. They are internal representations of a name that is used in one's code. (the name symbol refers to the fact that they are actually (syntactically sugared) access to the symbol table).


Symbols can get confusing when it is revealed that they can be approached as being as being names, as being strings, and even as objects. Symbols should be understood rather than seen in analogy -- but they are nontrivial to understand as they are an unusual language feature.

It may help to consider

  • ...symbols themselves as literal values
  • ...symbols a way to get a name within ruby without having to create a (string) object to look it up
  • ...that a symbol refers to a variable by name rather than by refrence
  • ...the construction as a low-level enumeration -- they are reusable names that always refer to the same thing, while their actual (internal) value usually doesn't really matter. (Note however that comparison to other languages doesn't help understanding most of the time)
  • ...them constants whose name is their value.

(...even though none of these is a complete or entirely correct description)



Information at a more technical level:

  • Symbols gets special treatment in that the parser can use them directly -- to fix references at parsing time rather than to leave things up to runtime (mutable-)string-based lookups.
  • It may help to know that the colon initializes a symbol object (in a similar way that other central data types such as strings, arrays, numbers also don't use new, but a more direct style in their object creation)
  • Symbols could have been purely internal, but they are exposed as objects (which which is a source of some confusion)


Symbols are useful in ruby because of a few properties of Ruby as a language:

  • each literal string implies creation of a new mutable string object (mentioning a literal string in code is actually a syntactic-sugared shorthand to a a String.new call). Each just happens to have the most visible piece of its state be the same as the other objects.
  • its strings are mutable by default
  • immutable (frozen) strings with the same value are not internally singular (the same object)(verify), so you do not save memory(verify) that way
  • Ruby (fairly sensibly) doesn't really have constants / constant enumerations (as such)


Every time you do something like:

thing["foo"]

You create a new string object, which will probably get cleaned up quite soon, and that creation and cleanup is two bits of overhead that you don't really want, and can avoid using symbols.

From this view, a symbol is a way to get a name within ruby without having to create an object.


Of course, you could create a string once, then refer to that created string each time. This avoids each mention of (say) "foo" creating a different string object with the same value, but does not make your code brief-and-readable.

From this view, you could say that symbols exist as an easy way to get something like constant identifiers. If you write :foo, each mention of :foo is, to the parser, exactly the same entry in the symbol table -- they are per definition all the same, avoiding the creation of many objects.


There is also possible confusion to passing symbols around.

You may have noticed that symbols are used more prominently in Ruby on Rails, which seems to be full of colons. This is mostly because inside Rails, Hashes are extended to transparently allow use of symbols as keys, more or less by making symbols and strings equivalent in that context -- which is a Rails design choice, and not true for Ruby in general.


As objects, symbols have things like integer and even string representations. It doesn't really contain these values as state, though, as objects generally do. Symbols as objects are hacks that allow you to use them this way(verify), but muddle the issue a bit.



Some code that may help

a = :foo
b = :"also a #$%! symbol"
c = :foo
d = :"foo"
# Both of these are true statements:
a==b
b==c
# ...because they have the same symbols (point to exactly the same symbol objects)
a.object_id
b.object_id
c.object_id
#...all give the same number


One way of approaching the use of symbols strings versus symbols is to consider that whenever you want the string contents of a named reference, you want a string. If only the (repeated) reference itself is important, symbols are nice and fast.


Some reading:

Arrays

Hashes

foo = {
  "bar" => 0xdeadbeef,
  "quu" => 'bar',
}

Key objects should not change their hash, which leads to arrays and hashes not being usable as keys.

Strings can be used as keys, because of some special-case handling -- basically meaning that the hash of a string won't change even if the string does. It is probably best to avoid this problem, and at least consider keys that are used as strings as being immutable

Regular expressions

Are syntactic-sugared into the language syntax, to make them easier to get to and use. You can also get them via Regexp.new

Ranges

Range objects represent a range.

Inclusive range:

1..5

Exclusive range:

1...5


Object-related syntax

Like most other OO languages, the dot (. character accesses object atributes / functions.


The question mark marks conditional things. For example:

s = 'foo'
s.frozen?   #is false
s.freeze
s.frozen?   #is true


The exclamation mark optionally marks object mutation. It is often used when there is a non-altering variation on the function that returns a new object with the requested change but leaves the original alone.


@instance_variable (basically self. (verify)) @@class_variable


Further object related notes

.dup generally constructs a new object with the same value

.clone generally clones the entire object state, including some ruby metadata such as whether it is frozen.



blocks

Omittable syntax