Skip to content
Advertisements

Tagruby

Ruby Class Members: Getter & Setter

The simplest example of read_attr, write_attr in a class.

class Person  
  attr_reader :name, :age   
  attr_writer :name, :age   # creates the setter methods       
    
  def initialize(name)  
    [@name](http://twitter.com/name) = name  
  end  
endmike = Person.new('Mike')   
mike.age = 20               # calling setter method  
mike.age                    # calling getter method, returns 20

Reference

The example is verbatim from an easy to follow tutorial on Ruby class: https://medium.com/@rondwalker22/how-getter-setter-methods-work-in-ruby-c5f5da07f99

Understanding Ruby Symbols

Ruby is an interpreted language. It is dynamically typed and uses a new memory for a variable. A variable has a name and a value. Symbols are an optimized variable that holds single instance of memory. It is good for variables that assume the same values across the program such as hash table keys.

h = {'my_key' => 123}

The storage for my_key is allocated each time my_key is used. That’s waste of memory and many related bookkeeping tasks by the Ruby interpreter.

So declaring the key as a symbol makes sense as only one copy of my_key is kept in memory.

h = {:my_key => 123}

You have to use the : operator with each usage of a symbol.

irb(main):003:0> new_hash={:my_key => 123}
=> {:my_key=>123}

irb(main):004:0> new_hash[:my_key]
=> 123

# You must use the :

irb(main):005:0> new_hash[my_key]
NameError: undefined local variable or method `my_key' for main:Object
    from (irb):5
    
irb(main):006:0> new_hash['my_key']
=> nil

Written with StackEdit.

Adding Query Params to a URL in Ruby with HTTP

The clearest example was in a StackOverflow post

require 'uri'

def add_param(url, param_name, param_value)
 uri = URI(url)
 params = URI.decode_www_form(uri.query || "") << [param_name, param_value]
 uri.query = URI.encode_www_form(params)
 uri.to_s
end

You can pass a map of params key & values and get expected URL.

Another example

 # prepare params.
 params = { 'id' => '12' }

 path = 'http://localhost/'
 uri = URI(path)

 uri.query = URI.encode_www_form(params)

Output

http://localhost?id=12

Reference

One More Reason to Avoid Ruby Language

Ruby is type unsafe language but it goes a step further and avoids checking dynamically too.

Consider this code

x = :abc
if x == 'abc'
  puts "Symbol and String are two different classes"
else
  puts x.class, 'abc'.class
end

# puts can print a symbol and string alike.
puts x

My Complaints

  • I’m new to Ruby. How could Ruby let a Symbol and String compare, in spite of being aware of their types? Like Python, it can throw an error.
  • How can puts print a Symbol as good as a String

References

A Resilient Web API Client in Ruby

Ruby HTTP client is not sophisticated enough to handle errors gracefully. I came across a well-designed client for a web service at [AppSignal].
(https://blog.appsignal.com/2018/05/16/ensure-retry-and-reraise-exceptions-in-ruby.html)

The code for the client is as following:

The code has the following logic:

  1. Try to establish a connection with the server.
  2. The request has a timeout and connection refused exceptions.
  3. If retries fail, code raise the last seen exception.
  4. Each retry has increased timeout.

Written with StackEdit.

%d bloggers like this: