I've got a pretty short question. Is it possible to initialize a hash with something like this:
row = {
:title => "row title",
:slug => row[:title].paremeterize
}
In other words, could I somehow reference an unitialized hash inside itself or I have to do it this way:
row = {
:title => "row ti开发者_运维问答tle"
}
row[:slug] = row[:title].paremeterize
Thanks for the comments. Of course, this code won't work. I asked if there is a similar way, maybe with a different syntax. Ruby has been full of surprises for me :)
You're going about this in a rather strange way. Try to think about what you are doing when you run into cases where you are trying to use the language in ways that are rarely documented (or impossible).
title = "foobar"
row = {
:title => title,
:slug => title.parameterize
}
Even better…
class Row
attr_accessor :title
def slug; title.parameterize; end
end
foo = Row.new :title => 'foo bar'
foo.slug #=> "foo-bar"
If you run the following in IRB,
row = {
:title => "row title",
:slug => row[:title]
}
you get the error NoMethodError: undefined method '[]' for nil:NilClass
. So no you can't do that, given that row
hasn't been fully initialized at that point and is a nil
object.
精彩评论