Ruby variable initialization

There is an execution path in the code below, where “bar” is not set before the test. Is it safe in Ruby? Will “bar” be initialized by default?

if foo
bar = true
end

if bar
puts "true"< br />end

Yes

Yes, it is Safe, because the worst case that can happen when referring to an uninitialized local is that a NameError exception will be raised.

In fact, your situation is a bit special. Because the parser will see bar before the reference, So even if foo is false, the method will not raise NameError, and the value of bar will be nil.

In the following code, there is an execution path, where “bar “Not set before testing, is it safe in Ruby? Will “bar” be initialized by default?

if foo
bar = true
end

if bar
puts "true"< br />end

Yes

Yes, it is safe, because it may be possible to refer to an uninitialized local The worst case that happens is that a NameError exception will be raised.

Actually, your situation is a bit special. Since the parser will see bar before the reference, the method will not raise even if foo is false NameError, and the value of bar will be nil.

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3354 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.