Abhinay
Abhinay

Reputation: 1816

Couldnt understand the Array behavior in ruby

i was writing code to append new email to an empty array in my Rails App. like this:

@users_email = Array.new 
@users_email << User.find_by_id(@comment.user_id).email 
@users_email << User.find_by_id(Comment.find_by_id(@parent_id).user_id).email if !@parent_id.nil?

Note: Here @comment is just a hash of id, user_id, parent_id and @parent_id is a the id of a Parent of any Comment. as in Hierarchy of Parent-child.

But instead of having two items in array ex: ["[email protected]", "[email protected]"] I am getting only one item ex:["[email protected]"] after appending second item.

My confusion starts when I try to save above expression in an Instance variable and tries to append the same into an empty array, It behaves as expected. Ex:

@users_email = Array.new
@first = User.find_by_id(@comment.user_id).email
@second = User.find_by_id(Comment.find_by_id(@parent_id).user_id).email if !@parent_id.nil?

@users_email << @first  # ["[email protected]"]
@users_email << @second  # ["[email protected]", "[email protected]"]

where as this wasn't the case in previous one. Can someone please explain whats happening here.

Update

By mistake I have place "=" instead of "<<" while appending first element to the array for the first case and after appending second one I got the result something like "[email protected]@xyz.com" but for some reason in my Rails Application I was getting only the first email id in return.ex: ["[email protected]"]

So, probably this question is now not relevant to the issue raised. Sorry for bugging all of you.

Upvotes: 1

Views: 54

Answers (1)

fny
fny

Reputation: 33635

That's because you have this check !@parent_id.nil? at the end of the following statement:

 @users_email << User.find_by_id(Comment.find_by_id(@parent_id).user_id).email if !@parent_id.nil?

In the first case, @parent_id apparently is nil, so the statement never executes: hence only one value is appended to the array.

Aside: prefer using the array literal syntax (ary = [] over ary = Array.new)

Upvotes: 1

Related Questions