0
class Human
  @core = "heart"

  def cardiovascular
    arr = ['heart','blood','lungs']
    core = @core
  end
end

Is the only way I am able to access @core directly by using this:

Human.instance_variable_get(:@core)  #=> "heart"

My understanding is that an instance variable is accessible from anywhere within the scope of the Class.

I am able to access the method by: Human.new.cardiovascular and I expect the return to be "heart" but the return I get is nil

  1. How come I can't access the instance variable as Human.core or Human.new.core?
  2. Why does the Human.new.cardiovascular return nil? (Shouldn't core == @core?)

Update

After putting @core within an initialize block I see the following output in IRB:

Human.new
=> #<Human:0x2f1f030 @core="heart">

This makes sense as it's now available to the entire Class, but how do I access the specific instance variables within the initialize block? Meaning, how do I get just: @core without calling the cardiovascular method in this case?

2

2 Answers 2

5

Do this:

class Human
  def initialize
    @core = "heart"
  end

  def cardiovascular
    arr = ['heart','blood','lungs']
    core = @core
  end
end

In short, you're setting instance variable on a class itself (which is an object too), but you want it on an instance.

Sign up to request clarification or add additional context in comments.

Comments

1

Also..

How come I can't access the instance variable as Human.core or Human.new.core?

Because, in Ruby, only methods can be accessed as such - not variables/fields. In this aspect, Ruby acts like SmallTalk (and unlike Python, Java, and many other OOP languages). The "accessor" (e.g. attr_accessor) methods create applicable proxies.

Why does the Human.new.cardiovascular return nil? (Shouldn't core == @core?)

Because @core in context is nil as explained in the other answers (and observations), however, the assignment core = @core is useless in the context (and this ties in with the previous question) because the local variable assignments are only accessible within that scope.

Note the correctness of the observation(s) - e.g. Human.instance_variable_get(:@core) works because it is an instance variable for the receiver (the Human class which is also an object), even if not for any instance of said class. Continue with this logic analysis, it's right :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.