Hello, I have a problem creating a function for my Rails application.
Uh, right there we come across our first misunderstanding: Ruby is not a functional programming language. It is an object oriented programming language. There is no function like function in Ruby. Ruby only uses methods that live on classes.
str = 'string here'
puts "It within the range!" if str.within_range?(3..30)
, , , . , String ( ).
, :
def within_range?(range)
if is_a?(String)
range.include?(size)
elsif is_a?(Integer)
range.include?(self)
end
end
within_range? , String. "" Object, () . , within_range? , , .
, :
:
undefined method `within_range?' for "":String
: -, , Ruby , "string here":String, "":String. , within_range? , 'string here', . , - , , , within_range? .
, . Ruby , Ruby within_range? , .. within_range? String , Object. ! ( ) Object. , , :
NoMethodError: private method `within_range?' called for "string here":String
, , , . Ruby on Rails, , .
. , String. , , , String Integer, , Object:
class Object
def within_range?(range)
if is_a?(String) then range.include?(size)
elsif is_a?(Integer) then range.include?(self) end
end
end
[ , self .]
. -: is_a? Ruby - . , - , , , - "-Rubyish", , . ( : , , , Ruby.)
, is_a? kind_of? Module#===, .
, , self. , case if:
class Object
def within_range?(range)
case self
when String then range.include?(size)
when Integer then range.include?(self) end
end
end
, . ! , . , , : , ! ( , , , , ...)
, , . : foo.bar, Ruby bar, foo. , .
, : ? , , , , . , Ruby , :
class String
def within_range?(range)
range.include?(size)
end
end
class Integer
def within_range?(range)
range.include?(self)
end
end
. : , within_range? , , , , , NoMethodError:
[].within_range?(3..30)
# => NoMethodError: undefined method `within_range?' for []:Array
else, nil, false , , , , .
: , , , . , Integer Numeric.
: , , , , Object.
, , : , String , , , .
( , Object), , ( ) . , , , . :
2.within_range?(1..3)
'B'.within_range?('A'..'C')
, , , , true. , B A C, .
: , . , , , , , , , .
length_within_range?, :
'B'.length_within_range?(1..2)
'B'.within_range?('A'..'C')
[, within_range? Object.]
, , , .
str.length_within_range?(3..30)
str.length.within_range?(3..30)
, , Object.
Object, , , ,
(3..30).include?(str.length)
.