Begin, Rescue and Ensure in Ruby?

Yes, ensure ensures that the code is always evaluated. That’s why it’s called ensure. So, it is equivalent to Java’s and C#’s finally. The general flow of begin/rescue/else/ensure/end looks like this: begin # something which might raise an exception rescue SomeExceptionClass => some_variable # code that deals with some exception rescue SomeOtherException => some_other_variable # … 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

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

Rails has an except/except! method that returns the hash with those keys removed. If you’re already using Rails, there’s no sense in creating your own version of this. class Hash # Returns a hash that includes everything but the given keys. # hash = { a: true, b: false, c: nil} # hash.except(:c) # => … Read more

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