How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

You’ve got a workable idea, but the #flatten! is in the wrong place — it flattens its receiver, so you could use it to turn [1, 2, [‘foo’, ‘bar’]] into [1,2,’foo’,’bar’]. I’m doubtless forgetting some approaches, but you can concatenate: a1.concat a2 a1 + a2 # creates a new array, as does a1 += a2 … Read more

Ruby: kind_of? vs. instance_of? vs. is_a?

kind_of? and is_a? are synonymous. instance_of? is different from the other two in that it only returns true if the object is an instance of that exact class, not a subclass. Example: “hello”.is_a? Object and “hello”.kind_of? Object return true because “hello” is a String and String is a subclass of Object. However “hello”.instance_of? Object returns … Read more

What’s the difference between equal?, eql?, ===, and ==?

I’m going to heavily quote the Object documentation here, because I think it has some great explanations. I encourage you to read it, and also the documentation for these methods as they’re overridden in other classes, like String. Side note: if you want to try these out for yourself on different objects, use something like … Read more

Checking if a variable is defined?

Use the defined? keyword (documentation). It will return a String with the kind of the item, or nil if it doesn’t exist. >> a = 1 => 1 >> defined? a => “local-variable” >> defined? b => nil >> defined? nil => “nil” >> defined? String => “constant” >> defined? 1 => “expression” As skalee … Read more

How do I pick randomly from an array?

Just use Array#sample: [:foo, :bar].sample # => :foo, or :bar 🙂 It is available in Ruby 1.9.1+. To be also able to use it with an earlier version of Ruby, you could require “backports/1.9.1/array/sample”. Note that in Ruby 1.8.7 it exists under the unfortunate name choice; it was renamed in later version so you shouldn’t … Read more

Why are exclamation marks used in Ruby methods?

In general, methods that end in ! indicate that the method will modify the object it’s called on. Ruby calls these as “dangerous methods” because they change state that someone else might have a reference to. Here’s a simple example for strings: foo = “A STRING” # a string called foo foo.downcase! # modifies foo … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)