Why do two strings separated by space concatenate in Ruby?

In C and C++, string literals next to each other are concatenated. As these languages influenced Ruby, I’d guess it inherits from there. And it is documented in Ruby now: see this answer and this page in the Ruby repo which states: Adjacent string literals are automatically concatenated by the interpreter: “con” “cat” “en” “at” … Read more

Rspec: expect vs expect with block – what’s the difference?

As has been mentioned: expect(4).to eq(4) This is specifically testing the value that you’ve sent in as the parameter to the method. When you’re trying to test for raised errors when you do the same thing: expect(raise “fail!”).to raise_error Your argument is evaluated immediately and that exception will be thrown and your test will blow … Read more

Match a string against multiple patterns

Use Regexp.union to combine them: union(pats_ary) → new_regexp Return a Regexp object that is the union of the given patterns, i.e., will match any of its parts. So this will do: re = Regexp.union(prefixes) then you use re as your regex: if name.match(re) #…

What does class_eval

__FILE__ and __LINE__ are sort of dynamic constants that hold the file and line that are currently executing. Passing them in here allow errors to properly report their location. instance_eval <<-end_eval, __FILE__, __LINE__ def foo a = 123 b = :abc a.send b end end_eval foo When you run this $ ruby foo.rb foo.rb:5:in `send’: … Read more

Why isn’t self always needed in ruby / rails / activerecord?

This is because attributes/associations are actually methods(getters/setters) and not local variables. When you state “parent = value” Ruby assumes you want to assign the value to the local variable parent. Somewhere up the stack there’s a setter method “def parent=” and to call that you must use “self.parent = ” to tell ruby that you … Read more

Ruby templates: How to pass variables into inlined ERB?

For a simple solution, use OpenStruct: require ‘erb’ require ‘ostruct’ namespace = OpenStruct.new(name: ‘Joan’, last: ‘Maragall’) template=”Name: <%= name %> <%= last %>” result = ERB.new(template).result(namespace.instance_eval { binding }) #=> Name: Joan Maragall The code above is simple enough but has (at least) two problems: 1) Since it relies on OpenStruct, an access to a … Read more