eggdrop
eggdrop

Reputation: 3366

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

Upvotes: 6

Views: 3369

Answers (3)

Kevin
Kevin

Reputation: 485

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.

Upvotes: 4

rnicholson
rnicholson

Reputation: 4588

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", ...

Upvotes: 8

nonopolarity
nonopolarity

Reputation: 151214

are you sure you didn't mean

user.username = "John"; user.hashed_password = "John";

i tried

>> a = 1; b= 2
=> 2

>> a
=> 1

>> b
=> 2

when something doesn't work, you can use one rule: always reduce it to the simplest case.

Upvotes: 1

Related Questions