cresjoy cresjoy - 1 year ago 73
Ruby Question

Assigning a function in variable

In Javascript we can do this

var c = {

firstname: "Bob",
lastName: "Smith"
log: function()
return "Hey" + this.firstname + " " + this.lastName;


Can we do anything like this in ruby? I.E where does the usage of "This" come in, and also can we stack functions inside a variable? I'm new to ruby but the feature of "hashes" seems awfully similiar in a sense

Answer Source

Hash items have no access to parent hash and hence hash’s nested siblings. What you are looking for is a class.

class MyClass
  def initialize
    @first_name = "Bob"
    @last_name = "Smith"

  def log
    "Hey #{@first_name} #{@last_name}"
#⇒ "Hey Bob Smith"

I believe it makes sense to read a book on Ruby syntax and/or basic concepts before trying to play with.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download