Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

semicolon as statement separator in Rails Console

The Rails console doesn't seem to like multiple ruby statements on the same line separated by a semicolon. Whenever I do this, the next line starts with ?> and I find that only the first statement was executed. Do you have to put each statement on a separate line?

>> user = User.new
user = User.new

=> #<User id: nil, username: "", hashed_password: "", first_name: "", last_name: "", email: "", display_name: "", user_level: 0, created_at: nil, updated_at: nil, posts_count: 0>

>> user.username = "John"; hashed_password = "John"; first_name = "John"; last_name = "coltrane"; email = "[email protected]"; display_name = "Johndispay"; user_level = 9; 
user.username = "John"; hashed_password = "John"; first_name = "John"; last_name = "coltrane"; email = "[email protected]"; display_name = "Johndispay"; user_level = 9; 

?> user.save
user.save

=> true

Everything except user.username = "John"; was ignored

like image 664
eggdrop Avatar asked May 30 '09 19:05

eggdrop


2 Answers

You need to say "user." so Ruby knows you mean to call the attribute assignment methods of the instance of user. Otherwise, you are just setting local variables called "hashed_password", etc.

>> user.username = "John"; user.hashed_password = "John"; user.first_name = "John"; user.last_name = "coltrane"; user.email = "[email protected]"; user.display_name = "Johndispay"; user.user_level = 9; 

Although, you could just pass a hash of the attributes you want to set on the new instance, like so

>> user = User.new(:username => "John", :hashed_password => "John", ...
like image 119
rnicholson Avatar answered Sep 21 '22 12:09

rnicholson


It's the trailing ; on your input. When you put a ';' on the end IRB will assume you want to add another statement. If you leave it off, it will evaluate all the statements and return the return value of the last one.

Sometimes if the method I'm calling is going to return a large array I will do something like this...

a = Account.entries; a.size

This will save the values I need and just output the size of the array instead of trying to dump it to the console, which can take a long time if it's large.

like image 34
Kevin Avatar answered Sep 18 '22 12:09

Kevin