Ruby - why assign parameters to instance variables? [closed] - ruby

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Sometimes I see code like
class Thing
def self.add_em(a,b)
a+b
end
end
and sometimes I see
class Thing
def self.add_em(a,b)
#a=a
#b=b
#a+#b
end
end
When/Why should I use the # instance variables instead of just using the parameters as passed?
I believe that one reason is if you want to use those variables in any other method then instance variables will be available and local, parameter based variables will not. However I frequently see # variables being used even though the variables are not being used in any other method.
So I see the pattern of
#a=a
#b=b
at the start of method for all parameters passed in being used a lot but I'm not clear exactly why if they are just used on that method. Is it just a convention in case they are used in other methods?

As you correctly realized, it does not make sense to define instance variables unless they are used in another method. If instance variables are used but are not called in any other method, then that code is probably not written by a good programmer.
But note that sometimes, method definitions are not obvious at first look. For example, if there is
class Thing
attr_reader :a
end
then there actually is a method that uses #a.

I'd say that they did it because they had plans to reference the arguments as instance variables. If not they failed the YAGNI (you aint gonna need it principle). If they changed their minds half way through (which has been known to happen...), they they forgot to tidy up.

Related

Check if ruby variable has changed [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a function that checks a software buffer for data, however if that data has not changed it is still added and sent.
So I end up getting data sent multiple times.
I'm trying to check to see if my variable has changed, and if it has not I want to prevent it from sending that data again.
Here is what I've tried.
$buffer = fldigi.add_to_buffer(msg)
if $buffer
fldigi.send_buffer()
else
puts "Debug(buffer): Data has not changed"
end
You might try wrapping $buffer in an object and then following the Observer Pattern. Any changes to $buffer must go through the wrapper object's methods. Observers can then subscribe to the change notification events emitted by the $buffer wrapper and act accordingly such as fldigi.send_buffer().
There's no way to know whether a variable has changed without tracing the execution of the program. Variables aren't objects in Ruby, you can't tell them to do something, you can't ask them questions, you can't pass them as arguments, you can't return them as values, you can't assign them to variables, you can't call methods on them.
There's only two things you can do with a variable: dereference it and assign to it.
Assignment is the only way to change the variable, therefore you need to trace assignments to the variable to figure out whether or not it was changed. Note, however, that the standard Ruby TracePoint API does not offer the necessary information (probably because variables might get optimized away by the compiler).
It is probably going to be much easier to just check whether some object has changed rather than whether some variable has changed.
prev_val = nil
loop do
new_val = fldigi.add_to_buffer(msg)
if new_val == prev_val
puts "Debug(buffer): Data has not changed"
else
fldigi.send_buffer()
end
prev_val = new_val
end

Most flexible function signature in golang [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have object initializer in my code, that initializes every field of my object explicitly. But in my case, most of the parameters have sensible defaults and I want to use them.
In Python I usually use combination of keyword arguments or defaults and my __init__ method contains some validation logic so I can use zero configuration principle in object initialization. For example:
class Foo:
"""This class designed to show zero configuration
principle in action"""
def __init__(self, mandatory, optional=None, **kwargs):
self.__field1 = mandatory
self.__field2 = optional or make_default2()
if 'bar' in kwargs:
self.__field3 = kwargs['bar']
else:
self.__field3 = make_default3()
f = Foo('mondatory', bar=Bar())
There is no parameters with default values in Go nor keyword parameters or function overloads. Because of that - it is difficult to write flexible initialization code (I don't care much about performance in such code usually).
I want to find most idiomatic way to write such code in Go. Maybe some combination of runtime type reflection and maps will do the job, what do you think?
Because newly-allocated memory in Go is always zeroed, the idiomatic way is to make explicit use of this fact by:
designing your structs to have have sane zero values
using composite literals
Take a look at the following section of Effective Go:
http://golang.org/doc/effective_go.html#data
For extremely complex cases, a configuration struct (option 3 at http://joneisen.tumblr.com/post/53695478114/golang-and-default-values) is also sometimes used, with a NewConfigStruct() that initializes a configuration instance with defaults. The user generates a default instance, sets the fields they want, then passes it to the New function for the actual struct they are creating.

Trying to make my first submission to the ruby project on github -- a new Array class instance method [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I recently answered a question on this site (Delete from Array and return deleted elements in Ruby) so well in my opinion that while writing I decided I'd try to submit a pull request for my nifty little method that would make ruby just a bit more awesome I think.
So I have a few questions, the most pressing of which is, Where is the Array class in ruby's source code? I can't find it. If its not there, is it in another repository that I should commit to? Or should I add it somewhere else in some initializer?
Where do new array methods like #uniq and #drop get added? Because I have a new one. #exclude.
To put it one way, #exclude is to #delete as #drop is to #shift. Just as #shift returns what has been removed from the array, so does #delete. #exclude is supposed to be like #drop for #delete. Extremely simple. Seems to work well.
class Array
def exclude(obj)
x = self
x.delete(obj)
x
end
end
I may also add a #pop equivalent for #drop, #popdrop or #backdrop. Am open to suggestions
class Array
def drop(n) #drop could have been implemented like this.
x = self
x.shift(n)
x
end
def popdrop(n)
x = self
x.pop(n)
x
end
end
I'm supposed to be working right now so don't have much time to edit this question. Mods let me know if I need to add more detail to the question -- specifically I just don't know where to put it. I've already forked the repo and am trying to just make a commit on github, which you can do now, but don't know where to put the code, or even if I should actually make a pull request at this point (sandbox?, IRC?, etc).
Ruby is coded in the language C for performance.
https://github.com/ruby/ruby/blob/trunk/array.c
You may be better off creating a gem, or writing a blog about it.
Otherwise you can write your Array deletion method in C. Here is the actual deletion method to help out.
https://github.com/ruby/ruby/blob/trunk/array.c#L2919

Rationale behind allowing Ruby constants to be re-defined and allowing access to private methods via send() method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
When we try to redefine a constant, Ruby shows only a warning, but not any error. So one can always redefine a constant in Ruby?
Also a private method of a class can be invoked using the send method:
Const = 12
puts Const
#only an warning: already initialized constant Const
Const = 14
puts Const #Displays 14
class MyClass
private
def priv
puts 'In private method'
end
end
obj = MyClass.new
#Error: private method `priv' called for #<MyClass:0x7f2cfda21738> (NoMethodError)
#obj.priv
#but this is fine!
obj.send(:priv)
Are there any rationale behind such designs in Ruby? Do not these violate the basic idea of constants and access specifiers respectively?
Is there any real, practical use of these designs? Some examples would be great if there are!
Note: I do see a lot of questions/discussions here regarding Ruby's constants and private methods, but I did not find anything related to the reason behind these.
As for send, the answer is rather simple: once you use reflection, all bets are off. Note that this is no different than in most other languages as well, you can also circumvent access restrictions in Java using reflection, for example.
And for constants, well, you do get a warning. You do get told that you are doing something you shouldn't. But Ruby is a language which trusts you that you know what you are doing. It won't get in your way. If you want to shoot yourself in the foot, you should be allowed to do that. Or, a more cynical way to look at it: there are so many evil things you can do in Ruby, redefining constants really doesn't matter that much.

using # instead of . in API documentation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
In API documentation, and sometimes even used in discussions here on Stack Overflow, I sometimes see the pound (#) character used instead of the dot (.) as the separator between the class name and the method name. For example:
Settings#maxPageSize
I'm wondering what this usage means, and where it comes from?
Assuming you mean Ruby (which is the first language that I can think of with such conventions), it is explained here:
Why are methods in Ruby documentation preceded by a hash sign?
I've always thought that the distinction is that Settings.maxPageSize seems to imply that you can actually write just that (i.e. that it is a static method), and that the pound is there to denote that it is just a reference to a method, not a piece of code that you can execute.
Although I could be totally wrong about this =)
So for static methods, you could actually reference them Settings.maxPageSize, but for instance methods, you'd have the option of coming up with a new convention, such as Array#sort to denote that something special is going on, or, to achieve the same completeness, you'd have to write
myArray.sort // when myArray is of the type Array
EDIT
Amadan's reply seems to confirm my interpretation, with the exception that Settings.maxPageSize is not used for static methods either; rather, that would be Settings::maxPageSize, and . being reserved entirely for example code, which makes sense to me.

Resources