I don't know how to implement regular expressions in Ruby. I tried this code, but it always returns true:
firstName = "Stepen123"
res = Validation_firstName(firstName)
puts res
def Validation_firstName(firstName)
reg = /[a-zA-z][^0-9]/
if reg.match(firstName)
return true
else
return false
end
end
I am not sure what I did wrong.
You can rewrite your method like this:
def validation_firstname(first_name)
!!first_name[/^[a-z]+$/i]
end
def validation_firstname(first_name)
first_name.scan(/\d+/).empty?
end
p validation_firstname("Stepen123") #=> false
p validation_firstname("Stepen") #=> true
Related
I am trying to recreate the enumerable module in Ruby. I am up to the any? method and having difficulty returning true or false. Instead each array item is returned 1 by 1.. Here is my code:
def my_any?
return self.to enum unless block_given?
self.each do |i|
return true if i == yield(i)
end
end
nums = [3,5,7,3,6,10,20,16]
puts nums.my_any?{|x|x==6}
Any ideas where I am going wrong?
You have three issues with your code: you should return an enumerator for this method when called without block, you should check just what yield returns, and you should explicitly return false on fail:
def my_any?
return to_enum(:my_any?) unless block_given?
each { |i| return true if yield(i) }
false
end
nums = [3,5,7,3,6,10,20,16]
puts nums.my_any? { |x| x == 6 }
#⇒ true
lazy = nums.my_any?
lazy.each { |x| x == 6 }
#⇒ true
Or, I would better use break:
def my_any?
return to_enum(:my_any?) unless block_given?
each { |i| break true if yield(i) } == true
end
You have two issues:
You're missing a return false if the loop fails to find a match. Currently when it fails to match, it'll give the return value from each, which is what you're seeing.
It's currently always failing, because while your return true if cond construct is right, any?'s conditional is not i == yield(i): you've got too many comparisons. You need just yield(i).
(The to enum bit sounds off too, but that's unrelated to your question.)
Slotting those changes into your code:
def my_any?
# FIXME: return self.to enum unless block_given?
self.each do |i|
return true if yield i
end
false
end
I have:
def user_validation
first_user_valid? || second_user_valid?
end
and I don't only want to return true/false but also want to return which method returns the true (maybe both?). I do have:
def user_validation
return true if first_user_valid?
return true if second_user_valid?
end
so far. But this does not seem very intuitive to me.
Thanks
You can return an array of responses:
def user_validation
[first_user_valid?, second_user_valid?]
end
This way you can know that the first returned true, and the other false...
# => [true, false]
If i were you, i change the return from boolean to int. Doing that, you can handle which statment returning specifics numbers for that.
Why not call the method itself separately for the different users?
def user_validation(user)
return user_valid?
end
if(user_validation(user_1))
//user_1 is valid
end
if(user_validation(user_2))
//user_2 is valid
end
Just out of curiosity:
result = %w|first_user_valid second_user_valid|.inject(nil) |memo, m|
(memo ||= []) << m.tr('_', ' ') if public_send("#{m}?")
memo
end
if result # at least one is valid
puts result.join ', '
else # none is valid
puts 'None is valid :('
end
Result here might be either nil (falsey), or the string like:
"first user valid, second user valid"
def user_validation
valid = ((which = :first) && first_user_valid?) ||
((which = :second) && second_user_valid?)
which = :neither unless valid
[valid, which]
end
To illustrate:
def first_user_valid?; true; end
def second_user_valid?; true; end
user_validation #=> [true, :first]
def first_user_valid?; false; end
user_validation #=> [true, :second]
def second_user_valid?; false; end
user_validation #=> [false, :neither]
In general, when using ||, you don't want to evaluate the second expression if the first evaluates true, as in some cases that may raise an exception (e.g. division by zero), have undesirable side effects (e.g., deleting a needed file) or initiate a lengthy calculation.
How is it possible to chain methods in Ruby when the method calls are specified as an array?
Example:
class String
def bipp(); self.to_s + "-bippity"; end
def bopp(); self.to_s + "-boppity"; end
def drop(); self.to_s + "-dropity"; end
end
## this produces the desired output
##
puts 'hello'.bipp.bopp.drop #=> hello-bippity-boppity-dropity
## how do we produce the same desired output here?
##
methods = "bipp|bopp|drop".split("|")
puts 'world'.send( __what_goes_here??__ ) #=> world-bippity-boppity-droppity
[Note to Ruby purists: stylistic liberties were taken with this example. For notes on preferred usage regarding semicolons, parenthesis, comments and symbols, please feel free to consult Ruby style guides (e.g., https://github.com/styleguide/ruby)]
Try this:
methods = "bipp|bopp|drop".split("|")
result = 'world'
methods.each {|meth| result = result.send(meth) }
puts result
or, using inject:
methods = "bipp|bopp|drop".split("|")
result = methods.inject('world') do |result, method|
result.send method
end
or, more briefly:
methods = "bipp|bopp|drop".split("|")
result = methods.inject('world', &:send)
By the way - Ruby doesn't need semicolons ; at the end of each line!
methods = "bipp|bopp|drop".split("|")
result = 'world'
methods.each {|meth| result = result.method(meth).call }
puts result #=> world-bippity-boppity-dropity
or
methods = "bipp|bopp|drop".split("|")
methods.each_with_object('world') {|meth,result| result.replace(result.method(meth).call)} #=> world-bippity-boppity-dropity
There is an array with 2 elements
test = ["i am a boy", "i am a girl"]
I want to test if a string is found inside the array elements, say:
test.include("boy") ==> true
test.include("frog") ==> false
Can i do it like that?
Using Regex.
test = ["i am a boy" , "i am a girl"]
test.find { |e| /boy/ =~ e } #=> "i am a boy"
test.find { |e| /frog/ =~ e } #=> nil
Well you can grep (regex) like this:
test.grep /boy/
or even better
test.grep(/boy/).any?
Also you can do
test = ["i am a boy" , "i am a girl"]
msg = 'boy'
test.select{|x| x.match(msg) }.length > 0
=> true
msg = 'frog'
test.select{|x| x.match(msg) }.length > 0
=> false
I took Peters snippet and modified it a bit to match on the string instead of the array value
ary = ["Home:Products:Glass", "Home:Products:Crystal"]
string = "Home:Products:Glass:Glasswear:Drinking Glasses"
USE:
ary.partial_include? string
The first item in the array will return true, it does not need to match the entire string.
class Array
def partial_include? search
self.each do |e|
return true if search.include?(e.to_s)
end
return false
end
end
If you don't mind to monkeypatch the the Array class you could do it like this
test = ["i am a boy" , "i am a girl"]
class Array
def partial_include? search
self.each do |e|
return true if e[search]
end
return false
end
end
p test.include?("boy") #==>false
p test.include?("frog") #==>false
p test.partial_include?("boy") #==>true
p test.partial_include?("frog") #==>false
If you want to test if a word included into the array elements, you can use method like this:
def included? array, word
array.inject([]) { |sum, e| sum + e.split }.include? word
end
Is there a good way to chain methods conditionally in Ruby?
What I want to do functionally is
if a && b && c
my_object.some_method_because_of_a.some_method_because_of_b.some_method_because_of_c
elsif a && b && !c
my_object.some_method_because_of_a.some_method_because_of_b
elsif a && !b && c
my_object.some_method_because_of_a.some_method_because_of_c
etc...
So depending on a number of conditions I want to work out what methods to call in the method chain.
So far my best attempt to do this in a "good way" is to conditionally build the string of methods, and use eval, but surely there is a better, more ruby, way?
You could put your methods into an array and then execute everything in this array
l= []
l << :method_a if a
l << :method_b if b
l << :method_c if c
l.inject(object) { |obj, method| obj.send(method) }
Object#send executes the method with the given name. Enumerable#inject iterates over the array, while giving the block the last returned value and the current array item.
If you want your method to take arguments you could also do it this way
l= []
l << [:method_a, arg_a1, arg_a2] if a
l << [:method_b, arg_b1] if b
l << [:method_c, arg_c1, arg_c2, arg_c3] if c
l.inject(object) { |obj, method_and_args| obj.send(*method_and_args) }
You can use tap:
my_object.tap{|o|o.method_a if a}.tap{|o|o.method_b if b}.tap{|o|o.method_c if c}
Sample class to demonstrate chaining methods that return a copied instance without modifying the caller.
This might be a lib required by your app.
class Foo
attr_accessor :field
def initialize
#field=[]
end
def dup
# Note: objects in #field aren't dup'ed!
super.tap{|e| e.field=e.field.dup }
end
def a
dup.tap{|e| e.field << :a }
end
def b
dup.tap{|e| e.field << :b }
end
def c
dup.tap{|e| e.field << :c }
end
end
monkeypatch: this is what you want to add to your app to enable conditional chaining
class Object
# passes self to block and returns result of block.
# More cumbersome to call than #chain_if, but useful if you want to put
# complex conditions in the block, or call a different method when your cond is false.
def chain_block(&block)
yield self
end
# passes self to block
# bool:
# if false, returns caller without executing block.
# if true, return result of block.
# Useful if your condition is simple, and you want to merely pass along the previous caller in the chain if false.
def chain_if(bool, &block)
bool ? yield(self) : self
end
end
Sample usage
# sample usage: chain_block
>> cond_a, cond_b, cond_c = true, false, true
>> f.chain_block{|e| cond_a ? e.a : e }.chain_block{|e| cond_b ? e.b : e }.chain_block{|e| cond_c ? e.c : e }
=> #<Foo:0x007fe71027ab60 #field=[:a, :c]>
# sample usage: chain_if
>> cond_a, cond_b, cond_c = false, true, false
>> f.chain_if(cond_a, &:a).chain_if(cond_b, &:b).chain_if(cond_c, &:c)
=> #<Foo:0x007fe7106a7e90 #field=[:b]>
# The chain_if call can also allow args
>> obj.chain_if(cond) {|e| e.argified_method(args) }
Although the inject method is perfectly valid, that kind of Enumerable use does confuse people and suffers from the limitation of not being able to pass arbitrary parameters.
A pattern like this may be better for this application:
object = my_object
if (a)
object = object.method_a(:arg_a)
end
if (b)
object = object.method_b
end
if (c)
object = object.method_c('arg_c1', 'arg_c2')
end
I've found this to be useful when using named scopes. For instance:
scope = Person
if (params[:filter_by_age])
scope = scope.in_age_group(params[:filter_by_age])
end
if (params[:country])
scope = scope.in_country(params[:country])
end
# Usually a will_paginate-type call is made here, too
#people = scope.all
Use #yield_self or, since Ruby 2.6, #then!
my_object.
then{ |o| a ? o.some_method_because_of_a : o }.
then{ |o| b ? o.some_method_because_of_b : o }.
then{ |o| c ? o.some_method_because_of_c : o }
Here's a more functional programming way.
Use break in order to get tap() to return the result. (tap is in only in rails as is mentioned in the other answer)
'hey'.tap{ |x| x + " what's" if true }
.tap{ |x| x + "noooooo" if false }
.tap{ |x| x + ' up' if true }
# => "hey"
'hey'.tap{ |x| break x + " what's" if true }
.tap{ |x| break x + "noooooo" if false }
.tap{ |x| break x + ' up' if true }
# => "hey what's up"
Maybe your situation is more complicated than this, but why not:
my_object.method_a if a
my_object.method_b if b
my_object.method_c if c
I use this pattern:
class A
def some_method_because_of_a
...
return self
end
def some_method_because_of_b
...
return self
end
end
a = A.new
a.some_method_because_of_a().some_method_because_of_b()
If you're using Rails, you can use #try. Instead of
foo ? (foo.bar ? foo.bar.baz : nil) : nil
write:
foo.try(:bar).try(:baz)
or, with arguments:
foo.try(:bar, arg: 3).try(:baz)
Not defined in vanilla ruby, but it isn't a lot of code.
What I wouldn't give for CoffeeScript's ?. operator.
I ended up writing the following:
class Object
# A naïve Either implementation.
# Allows for chainable conditions.
# (a -> Bool), Symbol, Symbol, ...Any -> Any
def either(pred, left, right, *args)
cond = case pred
when Symbol
self.send(pred)
when Proc
pred.call
else
pred
end
if cond
self.send right, *args
else
self.send left
end
end
# The up-coming identity method...
def itself
self
end
end
a = []
# => []
a.either(:empty?, :itself, :push, 1)
# => [1]
a.either(:empty?, :itself, :push, 1)
# => [1]
a.either(true, :itself, :push, 2)
# => [1, 2]