Ruby parameter type validation

Based on the Java background, I'm a little concerned about Ruby completely blasé about its method parameters. While in Java I could guarantee that the parameter x is the type necessary for the method to work correctly, in Ruby I have no way to guarantee that x is an integer, string, or something else for that matter.

Example: if I wanted to write the absolute_value method in Java, the header would look like

public static int absoluteValue(int x)

In Ruby, it will be something like

def self.absolute_value(x)

In this example, in Java code, I can be absolutely sure that the parameter passed is not "Happy Birthday!" but in the Ruby code I don't know that. How to prevent this situation in Ruby so that the code doesn't crash into Runtime?

+3
source share
5 answers

, . Java , Java .

, Ruby . , , ​​ , Java, , .

, . , , , , . , , , .

Ruby, .

, , , , , , .

Ruby . , RoR , , , , , , RSI .

+4

, . , . Ruby, , . , , .

+4

, .

a="String"
puts a.kind_of? Integer  # false
puts a.kind_of? String   # true

a=10
puts a.kind_of? Integer  # true
puts a.kind_of? String   # false
+2

Ruby (?) , , , . " duck typing" ( , , ), Ruby, Java Ruby. Ruby- .

+1

, . " "

def +(other)
  raise TypeError, "Point-like argument expected" unless other.respond_to? :x and other.respond_to? :y
  Point.new(@x + other.x, @y + other.y)
end

This example is used to implement the "+" operation in the Point class, which works with (x, y) purines. Instead of doing other.is_a? (Point) - they tested the implemented method, which seems to me a good option. It can be argued that the “other” object can have x and y attrs, which means something else, which, although the correct argument will be missed by the fact that I'm just pointing to the middle. My approach is also inclined towards making an addition directly and failing if someone passes the wrong type.

0
source

All Articles