Ruby: Check if a string contains multiple values [closed] - ruby

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 9 years ago.
Improve this question
I want to see if any arbitrary characters c1,c2,c3... turn up in a given string.
I'm looking for a nice way to rework the following example:
val = String.new("abc123")
if val.include? "a" or val.include? "2" or val.include? "3"
...
end

Try something like this
arr = [ 'a', '2', '3' ]
s = "abc123"
arr.any? { |letter| s.include? letter } # Will return true if any element is present

I would use a regular expression.
string_to_check = "hello random abc123"
string_to_check =~ /[a23]/
That would return the position where the first match is. Then if you would want to know if it is true or false you could just do == 0 or != 0
(string_to_check =~ /[a23]/) != 0

Write as below :
val = "abc123"
val[/[1af]/] # => "a"
val[/[w6f]/] # => nil
So change your code as
if val[/[a23]/]
#...
end
See the documentation of str[regexp] → new_str or nil.
If a Regexp is supplied, the matching portion of the string is returned. If a capture follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData is returned instead.

Related

Ruby - replace a letter for another Explanation for my code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
I got to solve the problem I was trying to solve, but the thing is that I am not sure why it worked, I just started adding methods.
So if anyone could explain why worked:
def replace(string1, letter_a, letter_b)
replacements = {letter_a => letter_b}
#this is the part I am not sure why is working:
initial_string.split('').map{|i| replacements[i] || i}.join
end
Firstly I recommend to use built-in methods String#gsub or String#tr
string.gsub(%r{#{replaceable_letter}}, replacing_letter)
"abcdef".gsub(/a/, "b") # => "bbcdef"
string.tr(replaceable_letter, replacing_letter)
"abcdef".tr("a", "b") # => "bbcdef"
Instead of initial_string.split('').map you can use initial_string.each_char.map
Explanation of your code:
replacements = {letter_a => letter_b}
is hash where replaceable letter is key and replacing letter is value
For example { "a" => "b" }
Than you split your string to chars array
After that map over this array
For every char you check the hash, for example:
replacements["a"] # => "b"
replacements["c"] # => nil
If hash has such key, you take replacing letter, if not take origin letter. Compare and read about || operator:
nil || "f" # => "f"
"b" || "a" # => "b"
And finally join new array

Introducing backslash and quote at beginning of string [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 want to convert "her" to "\"her".
I've tried using insert method:
>> "her".insert(0,'\"')
=> "\\"her"
and
>> "her".insert(0,'"')
=> ""her"
None of them gives me what I want: "\"her"
"her".insert(0,'"')
actually returns "\"her", which is what you said you wanted in the first place.
If you want to obtain "\"her\"", you might want to use Object#inspect:
"her".inspect
=> "\"her\""
Or, you can simply concatenate quotes at the beginning and at the end:
'"' + "her" + '"'
=> "\"her\""
If you just want "\"her"
a = "her".insert(0,'\"')
#=> "\\\"her"
puts a
#=> \"her
If you want output "\"her\""
a = "her"
#=> "her"
b = '\"'+a+'\"'
#=> "\\\"her\\\""
puts b
#=> \"her\"
I think your code is fine, you just don't know the meaning of \\ in console.
The first \ is escape character and second \ is character itself.
You will see \"her in the text foo.txt as you expected by:
File.write("foo.txt", "her".insert(0,'\"'))

Check whether string contains a full word [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 9 years ago.
Improve this question
Is there something in Ruby that returns true only if the string contains the whole word, in this case 'hello'?
I don't want the behavior of include? which returns true if only some characters within a word are present:
'hello whats up'.include? 'll'
=> true
> 'hownowbrowncow'['now'] => "now" # will be nil if not found
And if you want it to require word boundaries...
'hownowbrowncow'[/\bnow\b/] => nil
It doesn't really matter if it returns true or false, since anything other than nil or false will fulfill a conditional test. If you really like true and false, well, you can turn an arbitrary expression into true or false a number of ways, one way is:
'now'.nil? => false
!'now'.nil? => true
Lots of good ways to do this as others have given. Here's another way:
my_string.scan(/\w+/).include? "hello"
This would be a case-sensitive check. For case insensitive:
my_string.scan(/\w+/).map(&:downcase).include? "hello"
This will also work with a variable for "hello":
m_string.scan(/\w+/).map(&:downcase).include? my_word
str = "Hello guys, how are you?'"
keyword = "hello"
print str.split.map { |word| word.downcase }.include? keyword.downcase
If you mean only the alphabet, then you could
(! 'Wr4ngle'.gsub(/[A-Za-z]/, '').blank?)
That grep should be versatile enough for your needs
It sounds like you're asking to simply do:
"hello" == "hello"
If you don't want the match to be case sensitive, you could use:
"HeLlO".downcase == "hElLo".downcase
If you are looking to see if a string of characters includes another string of characters, you could do something like this:
s1 = "hello"
s2 = "oelhl"
s1.split("").sort == s2.split("").sort #=> case sensitive
s1.downcase.split("").sort == s2.downcase.split("").sort #=> not case sensitive

Regular expression for series of numbers in ruby [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 am trying to match a pattern as given below
pattern: file.update.20120304.xml
file.update.1.xml
file.update.201203040002.xml
If i have to match the pattern leaving the numbers file.update..xml
how can I do in ruby?
"file.update.20120304.xml"[/\d+/] # => "20120304"
"file.update.1.xml"[/\d+/] # => "1"
"file.update.201203040002.xml"[/\d+/] # => "201203040002"
You can use Regexp and gsub to extract the numbers
filename = 'file.update.20120304.xml'
numbers = filename.gsub(/\Afile\.update\.(\d+)\.xml\z/, '\1')
The used regexp is composed as following:
a first part file\.update\. to be sure you have "file.update"
a middle part ([0-9]+) to have one or more number
an end part \.xml to be sure to have ".xml" at the end
the anchors \A and \z for the beginning and the end of the string
The middle part is wrapped with () to be a Regexp variable that you can reuse in the replacement string as \1
Update with variableName[/regular expression/]
filename = 'file.update.20120304.xml'
numbers = filename[/\Afile\.update\.(\d+)\.xml\z/, 1]
It returns the first captured group, i.e. between ().
p "file.update.201203040002.xml".split(".") .map { |x| x if x.to_i != 0}.compact[0].to_i
#=> 201203040002
p "file.update.20120304.xml".split(".") .map { |x| x if x.to_i != 0}.compact[0].to_i
#=> 20120304

Regular expression inquiry [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'm using Ruby to do a simple substring type match. I'm trying to understand why the following happens:
irb(main):024:0> puts "match" if "foo" =~ /foo/
match
=> nil
irb(main):025:0> puts "match" if "foo" =~ /foo,/
=> nil
how can this regex be modified so that if any part of the search criteria matches "foo", a match is made?
You've got your comparisons backwards:
"foo".match(/foo,/) # See if "foo" matches the pattern "foo,"
# => nil
"foo,".match(/foo/) # See if "foo," matches the pattern "foo"
# => #<MatchData "foo">
The =~ operator is a bit of history that has fallen out of style because it's not self-explanatory.
You can use the scan method of String and pass in the regex you want to check against.
1.9.3p194 :008 > puts "match" if "foo".scan(/foo,/)
match
=> nil

Resources