irb - Method called on an object when displayed on the console in Ruby - Stack Overflow.
I generally first try .inspect
, if that doesn't give me what I want, I'll switch to .to_yaml
.
class User
attr_accessor :name, :age
end
user = User.new
user.name = "John Smith"
user.age = 30
puts user.inspect
#=> #<User:0x423270c @name="John Smith", @age=30>
puts user.to_yaml
#=> --- !ruby/object:User
#=> age: 30
#=> name: John Smith
Hope that helps.
define the to_s method in your model. For example
class Person < ActiveRecord::Base
def to_s
"Name:#{self.name} Age:#{self.age} Weight: #{self.weight}"
end
end
Then when you go to print it with #puts it will display that string with those variables.
In Rails you can print the result in the View by using the debug' Helper ActionView::Helpers::DebugHelper
#app/view/controllers/post_controller.rb
def index
@posts = Post.all
end
#app/view/posts/index.html.erb
<%= debug(@posts) %>
#start your server
rails -s
results (in browser)
- !ruby/object:Post
raw_attributes:
id: 2
title: My Second Post
body: Welcome! This is another example post
published_at: '2015-10-19 23:00:43.469520'
created_at: '2015-10-20 00:00:43.470739'
updated_at: '2015-10-20 00:00:43.470739'
attributes: !ruby/object:ActiveRecord::AttributeSet
attributes: !ruby/object:ActiveRecord::LazyAttributeHash
types: &5
id: &2 !ruby/object:ActiveRecord::Type::Integer
precision:
scale:
limit:
range: !ruby/range
begin: -2147483648
end: 2147483648
excl: true
title: &3 !ruby/object:ActiveRecord::Type::String
precision:
scale:
limit:
body: &4 !ruby/object:ActiveRecord::Type::Text
precision:
scale:
limit:
published_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
subtype: &1 !ruby/object:ActiveRecord::Type::DateTime
precision:
scale:
limit:
created_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
subtype: *1
updated_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
subtype: *1
I'm using the awesome_print gem
So you just have to type :
ap @var
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With