Why is it bad style to `rescue Exception => e` in Ruby?

TL;DR: Use StandardError instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing Exception is probably okay. Exception is the root of Ruby’s exception hierarchy, so when you rescue Exception you rescue from everything, including subclasses such as SyntaxError, LoadError, and Interrupt. Rescuing Interrupt prevents … Read more

What is attr_accessor in Ruby?

Let’s say you have a class Person. class Person end person = Person.new person.name # => no method error Obviously we never defined method name. Let’s do that. class Person def name @name # simply returning an instance variable @name end end person = Person.new person.name # => nil person.name = “Dennis” # => no … Read more

Compute percentage of cents total

There are a few things to consider in addition to the comments above about the elementary part of the question. This is money. You’re using floats (“to_f“) but they are not accurate; Google for details. Ruby provides alternatives. For example, require ‘bigdecimal’ and then use BigDecimal.new(self.total_seconds.to_s) instead of self.total_seconds.to_f. BigDecimal is a sledgehammer – slow … Read more

Converting an array of numbers to characters ruby [closed]

You create instance of Encrypted method, but you set @code = 2, @string = “Hello” and @encrypted = []. So if you call @encrypted[0], ruby return nil. So you can modify your class like this: class Encrypt def initialize(code, string) @code, @string, @encrypted = code, string, [] end def to_byte @string.each_byte { |c| @encrypted << … Read more

Very Basic Ruby puts and gets

It always helps if you include the error. There are two ways to fix that error: Interpolate the value: puts “you would like #{number} much better” Turn it from a number to a string: puts “you would like ” + number.to_s + ‘much better’ The former, #{…} syntax, evaluates the content of the braces as … Read more