Hash element reference inside itself

I have 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, can I somehow reference the unified hash inside myself, or should I do it like this:

 row = { :title => "row title" } row[:slug] = row[:title].paremeterize 

Thanks for the comments. Of course, this code will not work. I asked if there is a similar way, possibly with a different syntax. Ruby was full of surprises for me :)

+4
source share
2 answers

You are doing this rather oddly. Try to think about what you are doing when faced with situations where you are trying to use the language in a way that is 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" 
+6
source

If you do the following in IRB:

 row = { :title => "row title", :slug => row[:title] } 

You will receive the error message NoMethodError: undefined method '[]' for nil:NilClass . Therefore, you cannot do this, given that row not fully initialized at this point and is an nil object.

0
source

All Articles