i'm new ruby , new programming in general. have piece of code in standalone ruby script reads data yaml file , assigns data variable in method. done in method. outside definition of method, call method , print value of variable assigned. but, uh oh, value of variable assigned in method nil... why? has object oriented programming assume. can elaborate?
below code. thank in advance.
#!/usr/bin/env ruby require 'pg' require 'yaml' source_connection=nil def load_configurations file_name = nil argv.each do|a| file_name = "#{a}" end dest_options = yaml.load_file(file_name) source_connection = dest_options['dest_name'] end load_configurations() puts source_connection ##### returns nothing. why? #####
in ruby, in languages (all know @ least, javascript may exception) there concept called visibility scopes.
there 4 scopes in ruby:
- global scope
- class scope
- method scope
- block scope
what means in practice local variable defined ex. in method visible in method unless explicitly pass in (with method/block call param) or down (with return) call stack.
in case happens outside method assign source_connection
nil, refer same var name in different scope assigned there. ruby way of solving either define instance variable (@source_connection
) or explicitly pass variable method , return it.
pro tip: in ruby last evaluation gets returned default don't need explicitly write return source_connection
.
edit:
class instance , instance variables things little more complicated best if point in direction of metaprogramming ruby book lays out topics.
edit2:
rewrite suggestion (with little style change - method definition it's add parentheres no matter of there params or not. call on other hand may omit if there's none or single param - depends on personal taste ;) changed indent 2 spaces - think it's commonly used.
#!/usr/bin/env ruby require 'pg' require 'yaml' def load_configurations() file_name = nil argv.each do|a| file_name = "#{a}" end dest_options = yaml.load_file(file_name) dest_options['dest_name'] # ruby return last evaluation end source_connection = load_configurations puts source_connection # print expect
Comments
Post a Comment