cresjoy cresjoy - 6 months ago 16
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


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.